I have this small program in c and I am trying to understand how it works, it is a simple while loop that uses fork()
and wait()
to print out a few lines on the command line, I have commented to the best of my ability what I think is happening
for (i = 1; i <= 3; i++) /*simple while loop, loops 3 times */
{
pid = fork(); /*returns 0 if a child process is created */
if(pid == 0){ /*pid should be a 0 for first loop */
printf("Hello!\n"); /*we print hello */
return (i); /*will this return i to the parent process that called fork? */
} else { /*fork hasn't returned 0? */
pid = wait(&j); /*we wait until j is available? */
printf("Received %d\n", WEXITSTATUS(j)); /*if available we print "received (j)" */
}
}
This program is supposed to print:
Hello!
Received 1
Hello!
Received 2
Hello!
Received 3
When one of the child processes returns i
does the parent process wait for it as &j
? This is really confusing me, any help would be greatly appreciated.