I have a problem, I would like to do a fork for example a fork of 20processes, this fork created, should not do anything until the last one is not created, and I want to do it with semaphore, how can I implement it?
for (i=0; i<20; i++) {
switch (fork()) {
case: -1:
exit(EXIT_FAILURE);
case 0:
execve(....);
exit(EXIT_FAILURE);
default:
printf ("Child Created!");
}
}
Here's you homework. You can pay me later.
The idea is simple. Init the (necessarily, shared) semaphore to zero and make each child wait on it before it does its thing. When you're done forking in the parent, you post to the semaphore 20 times so that each child's
sem_wait
call completes.Same thing with with SysV semaphores:
Here you have to dance around the SysV IPC API ugliness and the need to set up an file-based key, but then, as a reward, you get to increment the semaphore by 20 in one go.