Reputation: 1729
I am learning OS development with C/C++ and i am using fork() method to experiment with process. I have the following code like this:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
fork(); //create a child process, currently total is 1 parent, 1 child
fork(); //create a child process,currently total is 2 parents, 2 child
pid_t pid;
if((pid=fork()) == 0) { //fork() and assign to pid, now has 4 parents, 4 childs
printf("I am the child: %u\n", getpid());
else {
printf("I am the parent: %u and my child is: %u\n", getpid(), pid);
}
}
When i compile it, and run it, it shows 4 parents and 4 children as i expected, however the output looks strange to me (notice the bolded line below where i get the output after user@slacker:~$).
user@slacker:~$ gcc forktest.c -o forktest
user@slacker:~$ ./forktest
I am the parent: 1183 and my child is: 1186
user@slacker:~$ I am the parent: 1184 and my child is: 1188
I am the parent: 1185 and my child is: 1189
I am the parent: 1187 and my child is: 1190
I am the child: 1186
I am the child: 1189
I am the child: 1190
I am the child: 1191
When i tried with 3 fork(), the output is even stranger. Can someone explain to me please?
Upvotes: 2
Views: 293
Reputation: 4332
fork fork fork
1183----+---------------+----------------+-------------------->
| | |
| | 1186 +-------------------->
| |
| 1185 +----------------+-------------------->
| |
| 1189 +-------------------->
|
1184 +---------------+----------------+-------------------->
| |
| 1188 +-------------------->
|
1187 +----------------+-------------------->
|
1190 +-------------------->
created with http://www.asciiflow.com/#Draw
Upvotes: 5