views:

710

answers:

2

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?
A: 

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;
Artelius
Threads are one thing; processes are another.
Jonathan Leffler
+3  A: 

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

The POSIX equivalents are:

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

Jonathan Leffler
you're i should work with those system calls. here's a great tutorial:http://www.cs.cf.ac.uk/Dave/C/node27.html
mmap() only required for POSIX, shmat() [at]taches the shm in System V IPC calls. (reply if incorrect!)
IanVaughan