gpt4 book ai didi

c - 关于 vfork() 系统调用?

转载 作者:行者123 更新时间:2023-12-04 10:13:30 25 4
gpt4 key购买 nike

#include <stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdio.h>
#include<stdlib.h>

int main()
{
pid_t child_pid = vfork();

if(child_pid < 0)
{
printf("vfork() error\n");
exit(-1);
}
if(child_pid != 0)
{
printf("Hey I am parent %d\nMy child is %d\n",getpid(),child_pid);
wait(NULL);
}

else
{
printf("Hey I am child %d\nMy parent is %d\n",getpid(),getppid());
execl("/bin/echo","echo","hello",NULL);
exit(0);
}
return 0;
}

输出:

 Hey I am child 4
My parent is 3
Hey I am parent 3
My child is 4
hello

我的问题:为什么在父进程执行后打印“hello”? 我已经开始学习 vfork()。谁能帮我解决这个问题?

最佳答案

父进程执行完毕后,进入wait(NULL);,阻塞父进程,直到子进程调用execl()exit

因此,当父进程被阻塞时,子进程调用 execl(),因此 hello 被打印在输出的末尾。

#include <stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdio.h>
#include<stdlib.h>

int main()
{
pid_t child_pid = vfork();

if(child_pid < 0)
{
printf("vfork() error\n");
exit(-1);
}
if(child_pid != 0)
{
printf("Hey I am parent %d\nMy child is %d\n",getpid(),child_pid);
wait(NULL);
}

else
{
printf("Hey I am child %d\nMy parent is %d\n",getpid(),getppid());
execl("/bin/echo","echo","hello",NULL);
exit(0);
}
return 0;
}

如果删除 execl(),子进程将转到 exit(0) 并且不会打印 hello

此外,在执行 execl() 之后,它会创建一个新进程,因此您在 execl() 之后编写的任何代码都不会被执行。根据手册页:-

The exec() family of functions replaces the current process image with a new process image. The functions described in this manual page are front-ends for execve(2). (See the manual page for execve(2) for further details about the replacement of the current process image.)

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

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