2015-11-09 89 views
1

即时了解fork(),但是在我的Ubuntu系统中出现了一些问题。进出口运行这段代码:fork(),首先运行父进程,然后运行子进程

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

int main(int argc, char **argv) 
{ 
printf("--beginning of program\n"); 

int counter = 0; 
pid_t pid = fork(); 

if (pid == 0) 
{ 
    // child process 
    int i = 0; 
    for (; i < 5; ++i) 
    { 
     printf("child process: counter=%d\n", ++counter); 
    } 
} 
else if (pid > 0) 
{ 
    // parent process 
    int j = 0; 
    for (; j < 5; ++j) 
    { 
     printf("parent process: counter=%d\n", ++counter); 
    } 
} 
else 
{ 
    // fork failed 
    printf("fork() failed!\n"); 
    return 1; 
} 

printf("--end of program--\n"); 

return 0; 
} 

我知道家长和孩子应该运行他们在没有特定的顺序代码,使代码应该返回是这样的:我每次运行程序时

-beginning of program 
parent process: counter=1 
parent process: counter=2 
parent process: counter=3 
child process: counter=1 
parent process: counter=4 
child process: counter=2 
parent process: counter=5 
child process: counter=3 
child process: counter=4 
child process: counter=5 
--end of program-- 

但,他们运行的似乎是相同的顺序。这里是我所得到的每一次我运行该程序捕获:

[email protected]:~/Documents/S-O$ ./sample 
--beginning of program 
parent process: counter=1 
parent process: counter=2 
parent process: counter=3 
parent process: counter=4 
parent process: counter=5 
--end of program-- 
[email protected]:~/Documents/S-O$ 
child process: counter=1 
child process: counter=2 
child process: counter=3 
child process: counter=4 
child process: counter=5 
--end of program-- 

好像父完成第一,然后孩子开始。但我想那不是真的。请注意,第二个shell提示是由程序本身打开的。任何可能发生的想法?

编辑:

,如果我把一个sleep(1)它工作得很好。我仍然认为,不应该总是有相同的执行顺序。即使计数到100,它也会给出相同的结果

+1

当你使用更大的数字时会发生什么?在每个循环中投入睡眠,看看会发生什么。 – ChiefTwoPencils

+1

你试过计数> 5吗? – John3136

+0

当我使用更大的数字时,它只是做同样的事情。 – angel208

回答

1

是父母和孩子以几乎不可预知的顺序运行他们的代码(请记住没有随机性),但是您的计划程序可能会在分派之后选择先安排父母,那么这个孩子。由于两者都有一个非常小的代码,因此父代能够运行其所有代码,然后运行子代。为了尝试其他的东西,你必须在两个过程分叉之后做更长的事情(例如你可以看到不同的输出交错)。

提示符不是由您的代码生成的,而是它的作用。当父进程死亡时,运行它的shell会得到控制权并提示您输入另一个命令,同时孩子们正在工作并污染您的终端。这个孩子已经成为一个孤儿过程。为了防止这种情况发生,您必须通过呼叫... wait()告诉家长等待其孩子。