c - Wait for all processes reach some point in program, then resume -


i have application creates many processes via fork(). @ point want pause them , wait until of them finish earlier tasks. start them @ once.

for (int = 0; < n; i++) {     if(fork() == 0)     {          //some operations here           <----- wait here n forked processes          //some operations want processes start @ similiar time 

i don't want of children quit.

this seems tailor-made semaphore. specifically, easy implement "system v semaphores". see semget(2) , semop(2).

the idea obtain semaphore in parent, initialize value n, have each child it's "ready" decrement value 1. children wait result become 0. voila.

here's sample program

#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h>  #define n       5  int main(int ac, char **av) {         int i, n, sem_id;         sem_id = semget(ipc_private, 1, 0777);          struct sembuf buf;         buf.sem_num = 0;         buf.sem_flg = 0;          // initialize semaphore value n         buf.sem_op = n;         n = semop(sem_id, &buf, 1);          // children same thing:         //    decrement semaphore value 1         //    wait semaphore value == 0          (i = 0; < n; ++i) {                 if (fork() == 0) {                         printf("child %d (%d) started\n", i, getpid());                         sleep(i + 1);   // sleep awhile.                         buf.sem_op = -1;                         n = semop(sem_id, &buf, 1);                         buf.sem_op = 0;                         n = semop(sem_id, &buf, 1);                         printf("child %d (%d) done\n", i, getpid());                         return 0;                 }         }         return 0; } 

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -