了解unix fork

时间:2014-06-27 20:35:25

标签: unix process fork

任何人都可以解释为什么包含" here"执行5次以及程序运行的准确程度因为我似乎不明白我是如何得到这个输出的

输出:

12958: 0 here
12959: 0
12958: 0 here
12958: 1 here
12960: 1
12958: 0 here
12958: 1 here

代码:

#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main(){
    int i;
    for(i=0; i<2; i++){
        printf("%d: %d here\n", getpid(), i);
        if(fork()==0){
            printf("%d: %d\n", getpid(), i);
            exit(0);
        }
    }
    for(i=0; i<2; i++){
        wait(0);
    }
    return 0;
}

编辑:因为我在计算机上运行Windows,我使用这个网站link检查代码,这可能是个问题吗?

2 个答案:

答案 0 :(得分:2)

Fork创建了一个几乎完全相同的进程,包括输出缓冲区。如果在fork之前没有刷新它们,则两个进程都可以最终打印内容。尝试在父母fflush(stdout);之后加printf

答案 1 :(得分:0)

不应该得到你提到的输出。当我测试你的代码时,我的输出是以下

11194:0

11194:1这里

11195:0

11196:1

也许你应该重新编译它并再试一次?

相关问题