首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用带有waitpid的Forks

使用带有waitpid的Forks
EN

Stack Overflow用户
提问于 2013-12-15 20:19:32
回答 1查看 780关注 0票数 0

是否有3个子进程和1个父进程?这两个不同的waitpid做什么,为什么会有两个呢?

代码语言:javascript
复制
int main()
{
    pid_t pid;

    int status, counter = 4;
    while(counter > 0)
    {
        pid = fork();
        if(pid)
        {
            counter /= 2;
        }
        else
        {
            printf("%d", counter); /* (1) */
            break;
        }
    }
    if(pid)
    {
        waitpid(-1, &status, 0);
        counter += WEXITSTATUS(status);
        waitpid(-1, &status, 0);
        counter += WEXITSTATUS(status);
        printf(";%d", counter); /* (2) */
    }
    return counter;
}

waitpid之后的第二个printf打印3、5、6、34、52、61 (不包括分号)。我不知道怎么会有两个数字的打印。我知道第二个数字可能来自while循环中的printf。

EN

回答 1

Stack Overflow用户

发布于 2013-12-16 13:58:12

是的,有3个子进程和1个父进程。子代返回4,2,1。

要收集所有状态,可以使用while循环:

代码语言:javascript
复制
if(pid)
{
  while (waitpid(-1, &status, 0) != -1) /* ignoring signals, errors */
    counter += WEXITSTATUS(status);
}
return counter;

在这种情况下,Parent返回7。

如果您只使用两个waitpid()调用,那么它们可能会返回{4,2,1}集合中的任何一对,例如,{4,1}{2,1},因此parent会相应地打印;5;3

由于stdio缓冲和fork()交互,输出可能会成倍增加。请参阅printf anomaly after “fork()”

可以在fork()之前使用fflush(),也可以在子代中使用write/_exit

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20594411

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档