int main(int argc, char *argv[]){ if (argc != 2){ puts("usage prog number_of_process"); exit(EXIT_FAILURE); } int num = atoi(argv[1]); int i; int * pids = malloc(sizeof(int)*num); for(i = 0; i < num; i++){ pids[i] = fork(); if(pids[i] == 0){ //This is the code of the child process printf("begin %d\n" , i); sleep(10); //simulation of work printf("finish %d\n", i); exit(EXIT_SUCCESS); } } //Waiting the finish of all child processes while(wait(NULL)){ if(errno == ECHILD) break; } }
Thursday, October 18, 2012
Multiple forks
This is the code for generate a dynamic number of process (with the system call fork()). The father wait that all the child processes finish.
Etichette:
C,
fork,
Programming,
Unix
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment