c - fork:子进程不会停留在无限循环中

标签 c linux fork

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

int main()
{
    pid_t pid;  

    pid = fork();
    printf("pid : %d\n", getpid());

    if( pid == 0)
    {
        printf("child: pid : %d \n", getpid());
        while(1);
    }
    else
    {
        printf("parent: pid : %d \n", getpid());
        //while(1);
    }
}

在上面的 if 语句中的代码片段中,如果我们放入 while(1),它不会保持阻塞状态,当按下回车键时,程序会退出,但是如果我们输入 while(1),父级将保持阻塞状态,直到我们按下 ctrl+c。请澄清 child 的这种行为。

最佳答案

In the above code snippet inside if statement if we put while(1), it doesn't remains blocked

子进程实际上并没有退出;它只是变成了 orphan process因为它的 parent 退出了。孤立的 chuld 进程将被系统的 init 进程采用。您可以通过 ps 命令查看它。

但是如果您将 while(1); 放在父进程中,它会保持阻塞状态。

基本上,无论哪个进程有 while(1); 无限循环,它仍在运行。当 parent 退出时,您会得到提示并且 child 成为孤儿。但是子进程还在运行。

一般来说,你需要wait(2)为父进程中的子进程收获子进程。

关于c - fork:子进程不会停留在无限循环中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47711423/

相关文章:

c# - 使用 VirtualProtect 将页面标记为写时复制(windows 上的穷人 fork )

c - 在 O(n) 时间内从 C/C++ 中的数组中删除重复项

objective-c - 创建的对象数量

c - 多进程环境中的多读单写同步?

r - 在 linux 上用 R 绘制图形时代码困惑

c - execl() 在参数中使用整数 (ping)

c - 如何在内存中创建游戏娃娃/炸弹?

在 GNU make 中一次编译多个 **changed** 源文件

php - 在 PHP 中运行 inkscape

c++ - 在 Linux x86_64 上使用单例 C++ 进行多处理