本文介绍了在C中创建访问共享内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个问题,我真的不知道该怎么办。我希望也许您可以让我知道如何处理它。

So I have a problem that I don't really know how to go about. I was hoping maybe you could let me know how to deal with it.

我需要在共享内存中分配N个缓冲区。每个缓冲区应初始化为0。然后,我必须派生N / 2个子进程。

I need to allocate N number of buffers in shared memory. Each buffer should be initialized to 0. Then I must fork N/2 number of child processes.

每个孩子(i)然后将值(i)写入缓冲区(i),睡眠一秒钟。然后读取当前缓冲区中的值,如果同时更改值,则会显示一条消息。然后孩子将i位置移动N / 2次。

Each child(i) then writes value (i) into buffer (i), sleeps for one second. Then reads the value at the current buffer, if the value changed in the mean time then it displays a message. The child then moves i-positions N/2 number of times.

So I can have
N Buffers = 11. (must be prime)
N/2 children = 5.

So child 2 would:
write into buffer 2, sleep, read from buffer 2. (now move 2 positions)
write into buffer 4, sleep, read from buffer 4. (now move 2 positions)
**remmeber we only have five buffers so we go around again*****
write into buffer 1, sleep, read from buffer 1. (now move 2 positions)
write into buffer 3, sleep, read from buffer 3. (now move 2 positions)
write into buffer 5, sleep, read from buffer 5. ***we stop moving here. N/2 moves already performed.






任何想法该怎么做?


Any ideas how this should be done?


  • 我可以只创建N个整数数组吗?由于所有子级都将访问相同的元素,因此会出现问题吗?

推荐答案

用于共享内存处理的经典System V IPC功能是:

The classic System V IPC functions for shared memory handling are:







  • shmget()
  • shmat()
  • shmdt()
  • shmctl()
  • ftok()

POSIX等效项是:

The POSIX equivalents are:




  • shm_open()
  • shm_unlink()

您使用将打开的共享内存对象加载到进程地址空间中。

You use mmap() to get the opened shared memory object loaded into a processes address space.

这篇关于在C中创建访问共享内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 23:31
查看更多