I recently ran into this piece of code, and don't fully understand it.
- What circumstances would cause pid == 0?
- Why does wait(NULL) cause the program to go into the if(pid == 0)
Basically I don't fully understand the output below. Any help would be appreciated. Thank you.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> // standard POSIX header file
#include <sys/wait.h> // POSIX header file for 'wait' function
int main(void)
{
int i = -1;
int pid;
pid = getpid();
fprintf(stdout, "parent pid = %d\n", pid);
pid = fork();
if (pid == 0)
{
for (i = 0; i < 10; ++i)
{
fprintf(stdout, "child process: %d\n", i);
sleep(1);
}
exit(0);
}
else
{
fprintf(stdout, "child pid = %d\n", pid);
fprintf(stdout, "waiting for child\n");
wait(NULL);
fprintf(stdout, "child terminated\n");
}
fprintf(stdout, "parent terminating\n");
return 0;
}
Output:
parent pid = 2896
child pid = 5840
waiting for child
child process: 0
child process: 1
child process: 2
child process: 3
child process: 4
child process: 5
child process: 6
child process: 7
child process: 8
child process: 9
child terminated
parent terminating