I've a very specific question about fork system call. I've this piece of code:
int main (void)
{
for (int i = 0; i < 10; i++) {
pid_t pid = fork ();
if ( !pid ) {
printf("CHILD | PID: %d, PPID: %d\n", getpid(), getppid());
_exit(i + 1);
}
}
for (int i = 0; i < 10; i++) {
int status;
waitpid(-1, &status, 0);
if (WIFEXITED(status)) {
printf("IM %d AND CHILD WITH EXIT CODE %d TERMINATED\n",
getpid(), WEXITSTATUS(status));
}
else {
printf("ERROR: CHILD NOT EXITED\n");
}
}
return 0;
}
which produces this output:
CHILD | PID: 3565, PPID: 3564
CHILD | PID: 3566, PPID: 3564
IM 3564 AND CHILD WITH EXIT CODE 1 TERMINATED
IM 3564 AND CHILD WITH EXIT CODE 2 TERMINATED
CHILD | PID: 3573, PPID: 3564
CHILD | PID: 3567, PPID: 3564
IM 3564 AND CHILD WITH EXIT CODE 9 TERMINATED
IM 3564 AND CHILD WITH EXIT CODE 3 TERMINATED
CHILD | PID: 3568, PPID: 3564
IM 3564 AND CHILD WITH EXIT CODE 4 TERMINATED
CHILD | PID: 3569, PPID: 3564
IM 3564 AND CHILD WITH EXIT CODE 5 TERMINATED
CHILD | PID: 3570, PPID: 3564
IM 3564 AND CHILD WITH EXIT CODE 6 TERMINATED
CHILD | PID: 3571, PPID: 3564
IM 3564 AND CHILD WITH EXIT CODE 7 TERMINATED
CHILD | PID: 3572, PPID: 3564
IM 3564 AND CHILD WITH EXIT CODE 8 TERMINATED
CHILD | PID: 3574, PPID: 3564
IM 3564 AND CHILD WITH EXIT CODE 10 TERMINATED
which makes me wonder how fork really works and what code new processes really execute. Looking at the above output results, I can not understand:
- How does second for cycle prints before first for finish all iterations? I've also noticed this second for is always executed by parent process, which makes me wonder if while on first for cycle,
if pid != 0
(which means parent process calling) second for cycle is executed (?) - Why does CHILD processes are not sorted printed by PID?
So, bottom line, how does fork really works and who executes what?