Creating accessing shared memory in 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.
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?
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.
Can I just create an array of N integers? Since all children will be accessing the same elements, will this be a problem?
Yeah, I think so. If you're using multiple threads, declare it like this:
volatile int sharedChannel[N];
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
volatile int *sharedChannel;
精彩评论