Ideally, this would be the case:
- There is one "hi" printed with each process (abbreviated as proc)
- Each fork doubles the number of process (each process spawns one child)
The calculation could be done by following each event:
- start: 1 proc
- fork: 2 x 1 = 2 procs
- print: 2 procs -> 2 hi's
- fork: 2 x 2 = 4 procs
- fork: 2 x 4 = 8 procs
- print: 8 procs -> 8 hi's
- fork: 2 x 8 procs -> 16 procs
Now we add up the the number of hi's:
2 + 8 = 10 hi's in total
However, this is not necessarily the case. On different systems, you may get different results.
A call to fork() causes a child process to be spawned that is identical to the parent.
If there is any buffering done when printing stdout and the buffers are not flushed before the next fork, then the child will appear to print when it "should not have". Refer to this question for some details on buffering.
This causes a different number of hi's to be printed an different systems.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…