How do processes branch out when you use fork() in

2019-09-21 09:54发布

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);
}

3条回答
你好瞎i
2楼-- · 2019-09-21 10:43

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.

查看更多
疯言疯语
3楼-- · 2019-09-21 10:54

Just unroll the loop:

int main() {
    int i;
    fork();
    printf("hi");
    fork();
    fork();
    printf("hi");
    fork();
    exit(0);
}
查看更多
霸刀☆藐视天下
4楼-- · 2019-09-21 10:55

I've used this code :

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(){
    int i; 
    for(i=0;i<2;i++)
    {
        fork();
        printf("hi from pid %d\n",getpid());
        fork();
    }
    exit(0);
}

Now i've piped the output to fk.out.

[aft@kruki sf]$ cat fk.out 
hi from pid 6698
hi from pid 6698
hi from pid 6699
.......................

Now look at this :

[aft@kruki sf]$ cat fk.out | awk '{print $4}' | sort | uniq | wc -l

8

There, you have it, you have 8 processes !. Don't coun't hi's. Because stdin buffer will switched back and forth, so counting hi's will be ambiguous.

查看更多
登录 后发表回答