c - trouble with forking 3 grandchildren from children, order and PID and PPIDs not right -
hi have question creating more children fork() based upon earlier question asked using fork() make 3 children out of 1 parent in c (not c++)
i want output (#s simplfied , used illustrate order)
[grandpa]hi pid 1234 , come ####(dont care number is) [dad] hi pid 2111 , come ppid 1234 [son] hi pid 3111 , come ppid 2111 [son] hi pid 3112 , come ppid 2111 [son] hi pid 3113 , come ppid 2111 [dad] hi pid 2112 , come ppid 1234 [son] hi pid 3111 , come ppid 2112 [son] hi pid 3112 , come ppid 2112 [son] hi pid 3113 , come ppid 2112 [dad] hi pid 2113 , come ppid 1234 [son] hi pid 3111 , come ppid 2113 [son] hi pid 3112 , come ppid 2113 [son] hi pid 3113 , come ppid 2113
but output looks this:
it seems ok @ end there regards dad ppid except last 1 , of pids seem out of order. don't know why there 1 son, 5, 3 sons. here code:
int grandforking(null) { gen1 (null); return 0; } int gen1 (null) { void about(char *); int i=0; int j=0; about("grandpa"); for(i = 0; < 3; i++ ) { pid_t child = 0; child = fork(); if (child < 0) { //unable fork error perror ("unable fork"); exit(-1); } else if (child == 0) { //child process gen2 (null); exit(0); } else { //parent process //(do nothing) } } for(j = 0; j < 3; j++ ) { wait(null);//wait parent acknowledge child process } return 0; } int gen2 (null) { int i=0; int j=0; about("dad"); for(i = 0; < 3; i++ ) { pid_t child = 0; child = fork(); if (child < 0) { //unable fork error perror ("unable fork"); exit(-1); } else if (child == 0) { //child process ("son"); exit(0); } else { //parent process //(do nothing) } } for(j = 0; j < 3; j++ ) { wait(null);//wait parent acknowledge child process } return 0; }
once processes launched, scheduler can , run them in order wishes. includes running several @ same time, if have more 1 processor. (like everyone, these days.)
it can launch child, run child while, , go parent print message.
you'd better ordering if had identifying printf before parent spawned children.
but way you'll lockstep ordering if like:
- identify oneself
- start of loop
- launch child
- wait child complete
- exit after children have completed
Comments
Post a Comment