I’m having some trouble with this program. I know what a fork() function does. It is used to create a new process from an existing process. The new process is called the child process, and the existing process is called the parent. The parent returnes the child’s pid and the child returns 0. That said, I find hard to understand what the two fork functions do in this program.
#include <unistd.h> #include <stdio.h> int main() { int i,y,x=1; for (i=0;i<4;i++) if(x && fork()) { y = i; x = 0; } if (x) y = i; fork(); printf("%in",y); }
Advertisement
Answer
Original process opens up a process when it enters the loop’s if
. The child does not enter the if
since fork() == 0
. Now the parent has x == 0
and no longer enters the following iterations’ if
s (short circuit &&
prevent fork
s).
note: short circuit if(x && fork())
prevents from forking twice since x == 0
=> no need to evaluate fork()
(true for all processes that forked once). A process that forked once never enters loop’s if
because x == 0
from that point on.
What you get is each loop value twice because each new process forks once the following iteration and outside the loop right before the print. There are no forks other than the first for each spawned process in the loop.
#include <unistd.h> #include <stdio.h> int main() { int i,y,x=1; for (i=0;i<4;i++) if(x && fork()) // only un-forked process (x=1) executes fork() { // only parent process (fork() != 0) execute this y = i; x = 0; } if (x) y = i; // set up i=4 for last forked process (has x=1) fork(); printf("%in",y); }
The process spawning process would look something like this:
tip: When investigating code like this you can add output statements (printf
) or use a debugger.