I'm having some hard time with synchronising N child process waiting each one of them to arrive at some specific point. I've tried semaphores and signals but I can't get my head around it.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/sem.h>
#include <sys/ipc.h>
#include <fcntl.h>
#include <semaphore.h>
#include <sys/wait.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/msg.h>
#define NUM_KIDS 4
void handle(int signum);
int main(int argc, char const *argv[])
{
sem_t* sem;
sem = sem_open("/ok", O_CREAT, 0);
signal(SIGUSR1, handle);
for(int i = 0; i < NUM_KIDS; i++) {
switch(fork()) {
case 0:
fprintf(stderr, "ready %d from %d\n", getpid(), getppid());
/* i would like that each child stop here untill everyone is ready */
for(int j = 0; j < 10; j++)
fprintf(stderr, "lot of stuff\n");
exit(0);
break;
default:
/* unleashing the kids when everyone is ready */
wait(NULL);
fprintf(stderr, "OK\n");
break;
}
}
return 0;
}
void handle(int signum) {;}
And I believe that the output should be (once the child are sync)
ready ... from xxx
ready ... from xxx
ready ... from xxx
ready ... from xxx
...lots of stuff... 10 times
...lots of stuff... 10 times
...lots of stuff... 10 times
...lots of stuff... 10 times
Synchronization
There's a simple trick:
If done correctly, the children all get EOF (zero bytes read) at the same time because there's no longer any process that can write to the pipe. (That's why it is important for the children to close the write end of the pipe before doing the synchronizing
read()
.)If you want the parent to know that the children are all ready, create two pipes before forking anything. The parent process closes the write end of this second pipe, and then reads from the read end. The children all close both ends of the pipe before settling into their
read()
call on the first pipe. The parent process gets EOF when all the children have closed the write end of the pipe, so it knows the children have all started, at least as far as closing the second pipe. The parent can then close the first pipe to release the children (and close the read end of the second pipe).Don't wait too soon!
You are waiting in the
default
clause of the switch, which is not correct. You need all four child processes launched before you do any waiting — otherwise they'll never all be able to synchronize. When you do wait, you'll need to do your waiting in a (new) loop. And, while debugging, you should add print statements to identify what is going on in the parent process. For example, you'll print the status of the processes that exit, and their PID:Working code
Sample run