linux - How to fork multiple processes from a same parent? -
i trying create multiple processes same parent, ended more processes expected. couldn't figure out how , need help here.
i found piece of code online , tried it,
int main () { pid_t pid=0; int i=0; (i=0; i<3; i++) { pid=fork(); switch(pid) { case 0: { cout<<"\ni kid , pid is:"<<getpid(); cout<<endl; exit(0); break; } default: { cout<<"\ni parent , pid is: "<<getpid(); cout<<"\nmy kid pid is: "<<pid; cout<<endl; wait(null); break; } } } homecoming 0; }
this code work , creates 3 children same parent. however, seems that's because after each kid process created, terminated immediately. won't fork more grandchild process in next round of loop. need maintain these kid processes running sometime , need communicate parents.
a kid process may break loop go on work outside
int main () { cout<<"\ni parent , pid is: "<<getpid()<<endl; pid_t pid; int i; (i=0; i<3; i++) { pid=fork(); if(pid == -1) { cout<<"error in fork()"<<endl; homecoming 1; } if(pid == 0) break; cout<<"my kid "<<i<<" pid is: "<<pid<<endl; } if(pid == 0) { cout<<"i kid "<<i<<" , pid "<<getpid()<<endl; wait(null); // edit: line wrong! } else { cout<<"i parent :)"<<endl; wait(null); // edit: line wrong! } homecoming 0; }
edit wait(null)
lines wrong. if process has no children active, wait()
has no effect, it's useless in children here. otoh in parent process wait()
suspends execution until any of children exits. have 3 children here, have wait()
3 times. additionally 1 can't know in advance order of children completion, need much more sophisticated code that. this:
struct work_description { int childpid; // other info - kid has } work[3]; for(i=1; i<3; i++) { pid=fork(); ... work[i].childpid = pid; } if(pid == 0) // in kid { do_something( work[i] ); } else { int childpid; while(childpid = wait(null), childpid != 0) { // kid terminated - find out 1 for(i=0; i<3; i++) if(work[i].childpid == childpid) { // utilize i-th kid results here } } // wait returned 0 - no more children wait }
linux c++ fork process
No comments:
Post a Comment