gpt4 book ai didi

c - vfork() 系统调用

转载 作者:太空狗 更新时间:2023-10-29 15:02:56 26 4
gpt4 key购买 nike

我读到使用 vfork() 系统调用创建的新进程作为父进程地址空间中的线程执行,直到子线程不调用 exit() 或 exec() 系统调用,父进程被阻塞。所以我用 vfork() 系统调用写了一个程序

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

int main()
{
pid_t pid;
printf("Parent\n");
pid = vfork();
if(pid==0)
{
printf("Child\n");
}
return 0;
}

我得到的输出如下:

 Parent  
Child
Parent
Child
Parent
Child
....
....
....

我假设 return 语句必须在内部调用 exit() 系统调用,所以我期望输出只有

Parent  
Child

有人能解释一下为什么实际上它没有停止并连续打印无限循环吗?

最佳答案

您应该阅读 vfork 的手册页非常仔细:

The vfork() function has the same effect as fork(2), except that the behavior is undefined if the process created by vfork() either modifies any data other than a variable of type pid_t used to store the return value from vfork(), or returns from the function in which vfork() was called, or calls any other function before successfully calling _exit(2) or one of the exec(3) family of functions.

(以上内容来自手册页的 POSIX 部分,因此(可能)适用于 Linux 以外的其他环境)。

您正在调用 printf 并从子进程返回,因此您的程序的行为是未定义的。

关于c - vfork() 系统调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6071670/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com