Please use [CODE] [/CODE]
tags around your code to make it more readable.
Originally Posted by mcy
printf("pid1: I am child %d\n",getpid());
printf("pid2: I am child %d\n",getpid());
my question is why there are two pid1 and not two pid2?
You obviously have four processes:
- The original process, let's call it A
- The child B created by the first fork in the original process
- The child C created by the second fork in the original process
- The child D created by the second fork in process B
The values of pid1
before the if clauses are:
- pid1==nonzero, pid2==nonzero
- pid1==zero, pid2==nonzero
- pid1==nonzero, pid2==zero
- pid1==zero, pid2==zero
The first if
clause will match in both B
. This is why you get two pid1 outputs: one by B
, the first child created by the original process, and one by D
, the child created by the second child created by the original process.
Because the second clause is else if
, it is only evaluated when the first one did not match; i.e., only for A
, the original process, and for C
, the second child created by the original process. Because pid2 is zero only for the latter, you only get one pid2 output, printed by C
, the second child created by the original process.
This is a very good example of why you should not do forks in succession: it is too easy to miss that all processes created by the first fork will execute the following forks
, unless you add the check that makes sure only the original process forks.