fork()
works the same way every time you call it. A new process is created as an exact copy of the current process, and both continue execution as if they both just returned from the fork()
function call, just with different return values. In your case you throw away that return value, so they're just identical processes.
Let's draw a picture for your first example. Sample output from a run I just made (since the output you put in your question is incomplete):
0. I am process 25597
1. I am process 25597
2. I am process 25597
1. I am process 25598
2. I am process 25599
2. I am process 25598
2. I am process 25600
You start with a single process with PID 25597. It prints the 0
line, and then forks. That yields two processes:
25597 # prints "0"
/
/
/
25597 25598 # both print "1"
So far so good. Now both of these new processes call fork()
again. The complete tree ends up looking like this:
25597
/
/
/
/
/
25597 25598 # both print "1"
/ /
/ /
/ /
25597 25599 25598 25600 # all four print "2"
The actual locations of 25599 and 25600 can't be guessed from the output, unfortunately - they could be the other way around, too.
For your 3-fork()
example, you just have to do the same thing, but it will have another level in the diagram - you'll end up with 8 processes each printing the "3" line.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…