在 C 中创建访问共享内存

标签 c shared-memory buffer

所以我遇到了一个问题,我真的不知道该怎么办。我希望你能告诉我如何处理它。

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

然后每个 child (i)将值(i)写入缓冲区(i),休眠一秒钟。然后读取当前缓冲区的值,如果值在此期间发生变化,则显示一条消息。然后 child 移动 i 个位置 N/2 次。

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.

知道应该怎么做吗?

  • 我可以只创建一个包含 N 个整数的数组吗?由于所有 child 都将访问相同的元素,这会成为问题吗?

最佳答案

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

POSIX 等价物是:

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

关于在 C 中创建访问共享内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1664519/

相关文章:

c - OpenCL - clEnqueueNDRangeKernel - 输出数组变为输入数组

c - C 中 get 的缓冲区溢出

c - SIGABRT 在 fopen 调用

在 C 中从 Fortran 调用全局字符串变量会导致段错误

c - 为什么在 C 中不能使用 [] 为字符串分配内存?

c - 字符串数组插入问题

c - UNIX SOCKET - 可以直接写入套接字的内存吗?

c# - 实例数据管理

python - 使用 fcntl 锁共享 mmap 协调?

c - 将结构存储在共享内存中是一种好习惯吗?