在 C 中创建访问共享内存
所以我有一个问题,我真的不知道如何解决。我希望你能让我知道如何处理它。
我需要在共享内存中分配 N 个缓冲区。每个缓冲区应该初始化为 0。然后我必须分叉 N/2 个子进程。
然后每个子进程(i)将值(i)写入缓冲区(i),休眠一秒钟。然后读取当前缓冲区中的值,如果该值同时发生变化,则显示一条消息。然后孩子移动 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 个整数的数组吗?由于所有孩子都将访问相同的元素,这会成为问题吗?
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.
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.
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?
- Can I just create an array of N integers? Since all children will be accessing the same elements, will this be a problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
用于共享内存处理的经典 System V IPC 函数是:
shmget()
shmat()
shmdt()
shmctl()
ftok()
POSIX 等效项是:
shm_open()
shm_unlink()
您使用
mmap()
将打开的共享内存对象加载到进程地址空间中。The classic System V IPC functions for shared memory handling are:
shmget()
shmat()
shmdt()
shmctl()
ftok()
The POSIX equivalents are:
shm_open()
shm_unlink()
You use
mmap()
to get the opened shared memory object loaded into a processes address space.是的,我想是的。如果您使用多个线程,请这样声明:
如果您使用单独的进程,并且使用一个函数来为您提供共享内存缓冲区,那么您将需要更多类似的内容
Yeah, I think so. If you're using multiple threads, declare it like this:
If you're using separate processes, and are using a function to give you a shared memory buffer, then you'll need something more like