I have two processes, A and B, that are using shared memory. I want process B to wait to use the shared memory until it is completely initialized by process A. To coordinate this, I am attempting to use a named semaphore.
// process A
sem_t *s = sem_open(SNAME, O_CREAT|O_RDWR, 0644, 0);
(create and initialize shared memory here)
sem_post(s);
// process B
sem_t *s = sem_open(SNAME, O_CREAT|O_RDWR, 0644, 0);
sem_wait(s);
(load and use shared memory here)
However, if I start process A first, process B will get stuck at sem_wait. This does not make sense to me, because I would assume that the sem_post(s) in process A will increment the counter in the named semaphore for process B, too, since it seems to be "shared" in a way.
What is the easiest way to modify this code to make sure that process B will wait for process A to initialize the shared memory, without assuming that process B will start first?
sem_post
increments the value and wakes waiting threads. Maybe usesem_getvalue
in process B to see if the value has already been incremented. If it hasn't then you cansem_wait
. (I'm not sure this really works across processes. There's a tiny window that can create a race condition.)