Reputation: 4114
If I run the following code :
#include <stdio.h>
#include <unistd.h>
int main()
{
pid_t pid, pid1;
fflush(stdout);
pid = fork();
fflush(stdout);
pid1 = fork();
if(pid==0)
{
printf("%d is the first child\n", getpid() );
}
else if(pid>0)
{
printf("%d is the first parent\n", pid);
wait();
}
if(pid1==0)
{
printf("%d is the second child\n", getpid() );
}
else if(pid1>0)
{
printf("%d is the second child\n", pid1);
wait();
}
return 0;
}
I get the output :
2896 is the first parent
2896 is the first child
2898 is the first child
2898 is the second child
2898 is the second child
2896 is the first parent
2897 is the second child
2897 is the second child
I cannot understand the output. Why are the same strings being printed multiple times ?
Upvotes: 5
Views: 19758
Reputation: 11
For better understanding, you can write your if/else block for each process:
if(pid != 0 && pid1 != 0){
printf("Parent P\n");//parent
}else if(pid == 0 && pid1 != 0){
printf("First child of P\n");
}else if(pid != 0 && pid1 == 0){
printf("Second child of P\n");
}else{
//pid = 0, pid2 = 0
printf("Child of the first child of P\n");
}
Upvotes: 1
Reputation: 1
Also i think you print same string mistakenly in this code below
else if(pid1>0)
{
printf("%d is the second child\n", pid1); // This "child" should be "parent"
wait();
}
Upvotes: 0
Reputation: 62777
You are doing total 3 forks: First, pid = fork()
is done in original process, resulting in one more process, so total is now two, both continuing from the next line in your code.
Then pid1 = fork()
is done on both of these, resulting in two more child processes, so total is now 4, each again continuing to next line (first if).
Then all three processes process the two if-else statements (assuming no fork errors), each process printing two lines. So four processes times 2 lines is 8 lines. Which you are getting.
So the processes are:
If you want to understand the output, step through the code in your mind for all of these four processes. It might also help if you print out current pid in each print statement, in addition to what you print now.
Upvotes: 11