繁体   English   中英

是否有异常的方法来终止子进程以获取此代码中的某些输出?

[英]is there an abnormal way to terminate a child process to get certain outputs in this code?

我是操作系统的新手,我发现了这个代码,我不明白为什么某些输出像:abc,我们无法假设我们在 c 中有这个代码:

    int main() 
{
    if(fork()==0)
        printf("a");
        else
        {
            printf("b");
            waitpid(-1);
        }
        printf("c");
    return 0;
}

waitpid() 等待子进程终止。 子进程可以以异常方式终止吗? 这样我们就可以得到这个输出:abc, bc?

至少根据fork的 linux 手册页:

RETURN VALUE
       On success, the PID of the child process is returned in the parent, and
       0  is returned in the child.  On failure, -1 is returned in the parent,
       no child process is created, and errno is set appropriately.

因此,如果您的子程序从未创建过,那么对于父进程,整个 output 将是c而对于子进程则没有,因为它从未出现过。

也有可能父进程在 output ac之前被杀死,那么你只会得到孩子的bc 或者也许父母在它甚至可以分叉之前就被杀死了! 有很多可能性,并且有很好的时机(以及中间的一些对sleep function 的调用)你可能会重现它们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM