join - C++ - fork() and its return value -



join - C++ - fork() and its return value -

i'm having troubles simple exercise. here code:

int main(int argc, char** argv) { pid_t pid1,pid2,pid3; int a=5,b=4,c=3,retval,retval2; pid1=fork(); if(pid1==0){ pid3=fork(); if(pid3==0) exit(a); else if(pid3>0){ waitpid(pid2,&retval2,0); cout<<wexitstatus(retval2); } } else if(pid1>0){ pid2=fork(); if(pid2==0){ cout<<"ciao"; exit(b); } else if(pid2>0){ waitpid(pid3,&retval,0); cout<<wexitstatus(retval); } } homecoming 0; }

as can see it's not complicated. want pid2(father) print pid3(son) homecoming value , pid3(father) print pid2(son) homecoming value. advice? appreciate much.

because of first fork (the 1 sets pid1), sec forks run in different processes. in pid1==0 branch, pid2 never gets value, because process never assigns one. likewise, in pid1>0 branch, pid3 never gets value.

it looks you're expecting 2 processes share same set of variables, doesn't work that. forking creates 2 independent processes, each own re-create of variables.

c++ join fork wait

Comments

Popular posts from this blog

javascript - I need to update the text of a paragraph by inline edit -

javascript - THREE.js reposition vertices for RingGeometry -

assembly - What is the addressing mode for ld, add, and rjmp instructions? -