In: Computer Science
The output of the following code is "11 0" But I am not sure why, can someone please explain to me clearly and concisely why this is the case?
main(){
int n=1;
if(fork())
wait(&n);
else
n=n+10;
printf("%d\n", n);
exit(0);
}
main(){
int n=1;
if(fork())
wait(&n);
else
n=n+10;
printf("%d\n", n);
exit(0);
}
fork() is a system call to create a process. When the fork() method is called a duplicate copy of itself is created called as child process. In the above code when fork() method is called a duplicate is created and this child process starts executing the lines return after calling fork method.
fork() method returns a negative value if no child process is created. It returns a positive pid number to the parent process if a child process is created. And it returns 0 to the child process if child process is created.
So in short if a child process is created then 0 is returned to child process and pid number of child is returned to parent process.
Now the above code after fork() is executed the code runs two times(one by parent process and another by child process).
There is a difference between wait() and wait(&n).
Summary of the output 11 and 0 :
Please leave a comment if u need more explanation.