fork()执行顺序?

时间:2015-01-08 12:09:12

标签: c linux gcc linux-kernel

int main () { 

    fork ();     
    fork ();     
    fork (); 

    pf (" hi\n"); 

} 

" hi"多少次?会打印吗? fork()的执行顺序是什么? os:linux编译器:gcc

1 个答案:

答案 0 :(得分:0)

问题1:" hi"会打印吗?

                      Due to first Fork
                             |
                   -------------------------
                   |                        |
             Due to second fork         Due to second fork
                   |                          |
          ----------------------            ----------------------------
        |                      |            |                          |
  Due to 3rd fork        Due to 3rd fork   Due to 3rd fork             Due to 3rd fork
        |                      |                |                           |
------------------       ---------------       ----------               ------------
|               |        |             |      |          |               |          |
process-1     process-2   process-3   process-4 pr-5     pr-6         process-7    process-8

所以 如果所有fork都顺利,则创建了总共8个进程,因此输出中将有8个或更少的hi

问题2:fork()的执行顺序是什么? os:linux编译器:gcc

无法保证首先安排哪个流程,以及哪一个流程。 一切都取决于Scheduler。