#include <stdio.h>
#include <sys/type.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
int main(void)
{
pid_t pid;
int i;
for(i=0; i<3; i++) {
pid = fork();
if(pid == -1) {
printf("Fork Error.\n");
} else if(pid == 0) {
printf("I am child");
}
}
if(pid != 0) {
while((pid = waitpid(-1, NULL, 0)) > 0)
if(errno == ECHILD)
break;
printf("I am parent and all children have exited.\n");
}
exit(0);
return 0;
}
The result is that,
'I am child' is printed 7 times, 'I am parent and all children have exited.' is printed 4 times
and the print sequence is not fixed.
I figured out some of the questions that I have been struggling with, but some are not. So, here it is.
Why 'I am parent and all children have exited.' is printed 4 times?
Could you explain it in detail?
PS. I know that sys/wait.h needs to be inserted on top of the code, but my boss doesn't want me to do so.