fork的输出不正确

时间:2012-07-17 12:59:57

标签: c fork

考虑以下程序的输出:

int main()
{
    int ret;
    ret=fork();
    ret=fork();
    ret=fork();
    ret=fork();

    if(!ret)
            printf("one\n");
    else
            printf("two\n");
    return 0;
}

我得到的输出为:

two
one
two
two    

http://ideone.com/omgKm

AFAIT,输出应为8 times one& 8 times two

其余的one's& two's

1 个答案:

答案 0 :(得分:4)

考虑这个替代代码,它可以跟踪更好的内容:

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

int main(void)
{
    int ret1 = fork();
    int ret2 = fork();
    int ret3 = fork();
    int ret4 = fork();

    if (ret4 == 0)
        printf("one: (%d: %d, %d, %d, %d)\n", (int)getpid(), ret1, ret2, ret3, ret4);
    else
        printf("two: (%d: %d, %d, %d, %d)\n", (int)getpid(), ret1, ret2, ret3, ret4);
    return 0;
}

向我们展示此变体的输出,我们可以看到哪些有效,哪些失败。


在看到替代输出后,我在我的Mac上得到了此信息(Isis JL:是我的提示,而rmkmake的替代实现):

Isis JL: rmk fb && ./fb
    /usr/bin/gcc -O3 -g -std=c99 -Wall -Wextra fb.c -o fb  
two: (38068: 38069, 38070, 38071, 38072)
one: (38072: 38069, 38070, 38071, 0)
two: (38071: 38069, 38070, 0, 38075)
two: (38070: 38069, 0, 38074, 38077)
two: (38073: 0, 0, 38078, 38079)
two: (38069: 0, 38073, 38076, 38080)
one: (38075: 38069, 38070, 0, 0)
one: (38077: 38069, 0, 38074, 0)
Isis JL: two: (38074: 38069, 0, 0, 38081)
two: (38078: 0, 0, 0, 38082)
one: (38079: 0, 0, 38078, 0)
one: (38081: 38069, 0, 0, 0)
two: (38076: 0, 38073, 0, 38083)
one: (38080: 0, 38073, 38076, 0)
one: (38083: 0, 38073, 0, 0)
one: (38082: 0, 0, 0, 0)

Isis JL:

请注意交错提示 - 结尾处的空白行是输出完成后我点击返回的位置。

假设:

初始进程停止后,不会捕获ideone上的输出。

尝试这种替代方案,等待儿童在退出前死亡:

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

int main(void)
{
    int ret1 = fork();
    int ret2 = fork();
    int ret3 = fork();
    int ret4 = fork();

    if (ret4 == 0)
        printf("one: (%d: %d, %d, %d, %d)\n", (int)getpid(), ret1, ret2, ret3, ret4);
    else
        printf("two: (%d: %d, %d, %d, %d)\n", (int)getpid(), ret1, ret2, ret3, ret4);
    while (wait(0) > 0)
        ;
    return 0;
}

再次在Mac上输出:

Isis JL: rmk fb && ./fb
    /usr/bin/gcc -O3 -g -std=c99 -Wall -Wextra fb.c -o fb  
two: (38111: 38112, 38113, 38114, 38115)
one: (38115: 38112, 38113, 38114, 0)
two: (38114: 38112, 38113, 0, 38119)
two: (38113: 38112, 0, 38117, 38121)
two: (38117: 38112, 0, 0, 38123)
one: (38119: 38112, 38113, 0, 0)
two: (38118: 0, 38116, 0, 38124)
one: (38121: 38112, 0, 38117, 0)
one: (38125: 0, 0, 38122, 0)
two: (38116: 0, 0, 38122, 38125)
two: (38122: 0, 0, 0, 38126)
two: (38112: 0, 38116, 38118, 38120)
one: (38120: 0, 38116, 38118, 0)
one: (38123: 38112, 0, 0, 0)
one: (38124: 0, 38116, 0, 0)
one: (38126: 0, 0, 0, 0)
Isis JL:

假设证明

在某种程度上你可以证明什么...... http://ideone.com/zFoLn ......

显示所有16行输出。问题一定是“提前终止”。