c - vfork 永不返回

标签 c linux fork

为什么这个程序永远不会返回并继续创建子进程?

int main()
{
    pid_t pid;
    int foo1 = 1, foo2 = 2;
    printf("before fork()\n");

    if ((pid = vfork()) < 0 ) {
            printf("fork failed.\n");
    }else if (pid == 0) {
            foo1++;
            foo2++;
            printf("child process: pid is %d, my parent pid is  %d\n", getpid(), getppid());
    }else if (pid > 0){
            printf("parent process: pid is %d\n", getpid());
    }

    printf("%s: foo1 is %d, foo2 is %d\n",pid == 0 ? "child process" : "parent process", foo1, foo2);
    return 0;
}

输出如下:

before fork()
child process: pid is 17244, my parent pid is  15839
child process: foo1 is 2, foo2 is 3
parent process: pid is 15839
parent process: foo1 is -1079005816, foo2 is -1218256081
before fork()
child process: pid is 17245, my parent pid is  15839
child process: foo1 is 2, foo2 is 3
parent process: pid is 15839
parent process: foo1 is -1079005816, foo2 is -1218256081
before fork()
.....
.....

如果在第二个 if block 中添加一个 _exit 就可以了。 我知道 vfork 与父进程共享相同的地址空间,但如果程序以崩溃而不是无限循环结束则更合理。

最佳答案

vfork 是一个非常棘手的系统调用,它的唯一用途是立即在子系统中拥有一个 execve - 对于其他类型的用途,它是危险且不可预测的。

另请注意,与 fork 不同,父级会暂停,直到子级退出或调用 execve

关于c - vfork 永不返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6676436/

相关文章:

c - Select() 永远不会返回 true

linux - Jenkins Pipeline 启动 Protractor Selenium 服务器,然后永远卡住

c - Unix 进程 fork 层次结构

c - telnet 在发送数据时是否添加任何额外的字节?

c - 查找数组中重复数字的算法---Fastest Way

C Sendto 重复执行时不起作用

linux - 谁在刷新 Linux 中的硬件看门狗?

c - pipe() 从 1 个父进程到单独的 c 文件中的多个子进程

c - SSL_CTX_new 中的段错误

c - fwrite() 是如何工作的