Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

c - How do processes branch out when you use fork() in a for loop?

fork() calls outside a loop are easy to figure out, but when they are inside a loop I find it difficult. Can anyone figuratively explain how the processes branch out with an example like this one?

#include <stdio.h>

int main(){
    int i; 
    for(i=0;i<2;i++)
    {
        fork();
        printf("hi");
        fork();
    }
    exit(0);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...