In your code, in each loop the parent-process is creating a child-process; the child-process is printing its message, while the parent-process is waiting for this specific child-process's exit status to be collected before re-entering the loop. Working like this, i+1
-th child-process won't be created until i
-th child-process terminates.
To see what you expected, your code could look like this (although not using __WALL
option here):
pid_t pid;
for (int i = 0; i < N; i++) {
if ((pid = fork()) == -1)
return -1; // error, returning from parent
if (pid == 0) {
printf("child: %d\n", i);
exit(0); // child i has finished
}
}
for (i = 0; i < N; i++)
waitpid(-1, NULL, 0); // waiting for all children
printf("I'm parent. All children have finished.\n");
In this case, the parent-process will first create N
processes before it starts to collect their exit status. When it finishes waiting, the proper message will be printed.