I have the following code:
#include <stdio.h>
main(int argc, char *argv[])
{
int n,st;
n = atoi(argv[1]);
while(n*fork()) {
printf("%d %d\n",getpid(), getppid());
n--;
printf("%d\n", wait(&st));
printf("------\n");
}
}
I execute this code and I get the following results:
bash-3.2$ ./test 3
10218 9948
10219
------
10218 9948
10220
------
10218 9948
10221
------
here are my thoughts:
The parent is creating a child:
10218 9948
But after, I don’t understand why the printf("%d\n", wait(&st)); returns this id: 10219.
The wait() should return the id of the child that terminates.
Can anyone help?!
Wait is not blocking because there’s no reason to block. The child has already finished execution. This is because Linux will schedule the “child” process to run first.
Here is what’s happening in graph form: