I have this program
childpid = 0;
int i, n;
for(i=1; i < n; i++)
if((childpid = fork())
break;
fprintf(stderr, "i:%d process ID: %ld parent ID: %ld child ID: %ld\n,
i, (long)getpid(), (long)getppid(), (long)childpid);
return 0;
It says that since a parent's process's childpid variable does not have a value of 0, it will break out of a loop. A a child process's pid is 0, and will become a parent in the next iteration.
To my knowledge, a new process is created with the code after the line fork() has been called. If a parent process breaks out of the loop as its childpid is not 0, does that not mean that the printf statement will be run once and the program will terminate since the loop has ended? I am confused about how this program runs.
I also have this code
for(i=1; i < n; i++)
if( ((childpid = fork()) <= 0)
break;
fprintf(stderr, "i:%d process ID: %ld parent ID: %ld child ID: %ld\n,
i, (long)getpid(), (long)getppid(), (long)childpid);
return 0;
This creates a fan of processes and does the opposite of the first program. The child process breaks out of the loop since its chilpid is equal to 0, and the parent processes run in the loop.
I have an exam on Monday, and I've understood everything else please do help :/
