fork() execution in for loop

倾然丶 夕夏残阳落幕 提交于 2019-12-20 05:19:14

问题


int main(int argc, char** argv) {
    int i = 0;
    while (i < 2) {
        fork();
        system("ps -o pid,ppid,comm,stat");
        i++;
     }
     return (EXIT_SUCCESS);
}

Can anyone tell me how many times ps command is executed with an explanation?


回答1:


I believe the answer is 6.

in the first iteration, fork() is called, splitting the process in 2, thus calling ps twice.

in the second iteration, fork is called again in each process, so you now have 4 processes running ps.

total calls to ps: 2+4=6.




回答2:


6 times.

It creates a process tree like this:

A-+
  |-B-+
  |   |-C-+
  |-D

A does it twice (i=0)

B does it twice (i=0)

C does it once (i=1)

D does it once (i=1)

Note that my usage of letters is to distinguish them. There's no predictable output ordering since process switching is non-deterministic to the eyes of a programmer.




回答3:


Initial Process
i == 0
-> Fork 1
   system call
   i == 1
   -> Fork 1.1
      system call
   system call
system call
i == 1
-> Fork 2
   system call
system call

I count 6, 2 each from the initial process and the first fork (4), and one from each process forked when i == 1 from those 2 processes.

Of course that's assuming you fix the missing end brace (and define EXIT_SUCCESS), otherwise none, since it won't compile. :-)



来源:https://stackoverflow.com/questions/7138491/fork-execution-in-for-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!