gpt4 book ai didi

linux - 在程序中使用fork时执行

转载 作者:太空宇宙 更新时间:2023-11-04 09:01:03 25 4
gpt4 key购买 nike

当我尝试下面的程序时,我正在阅读有关 fork() 的内容。我无法理解以下命令的输出,但如果我删除第二个 fork() 调用,我可以弄清楚它会做什么。请解释一下下面程序的流程。

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <error.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;
int main(int argc, char const *argv[])
{
pid_t pid;
int returnvalue;

pid = fork();
pid = fork();
if (!pid) cout<< "In the child"<<endl;
else cout<< "In parent"<<endl;
cout<< (&returnvalue)<<endl;
switch(pid)
{
case -1:
perror("fork");
return 0;
case 0:
cout<< "Child Process with pid: " <<getpid()<<endl;
cout<< "Parent's pid is: "<<getppid()<<endl;
cout<< "Exiting"<<endl;
returnvalue=2;
return returnvalue;
default:
cout<< "Parent process with pid: "<<getpid()<<endl;
cout<< "Child's pid: "<<pid<<endl;
cout<< "Waiting for child to exit"<<endl;
wait(&returnvalue);
cout<< "Child's exit status: "<<WEXITSTATUS(returnvalue)<<endl;
cout<< "Exiting!"<<endl;

}
return 0;

为什么它会分别打印两次“In parent”和“In the child”?另外,我读到每个子进程都有自己的变量副本。 “returnvalue”的地址不应该打印不同吗?输出:

In parent
0x7fff2d536428
Parent process with pid: 5487
Child's pid: 5489
Waiting for child to exit
In the child
0x7fff2d536428
Child Process with pid: 5489
Parent's pid is: 5487
Exiting
Child's exit status: 2
Exiting!
In parent
0x7fff2d536428
Parent process with pid: 5488
Child's pid: 5490
Waiting for child to exit
In the child
0x7fff2d536428
Child Process with pid: 5490
Parent's pid is: 5488
Exiting
Child's exit status: 2
Exiting!

最佳答案

好吧,你确实有 2 次调用 fork() 将导致 4 个进程。

1st fork in P1 --> new process P2
2nd fork in P1 --> new process P3
2nd fork in P2 --> new process P4

为了便于解释,pid 将根据第二次 fork() 之后的结果而有所不同,我只说 P1 是父级并且仍然是父级,P2 是 P1 的子级,但是是父级P4 的 pid,因此它的 pid 将不为零,P3 和 P4 的 pid 都将等于 0。所有 4 个进程将进入 switch 语句,其中 pid 将它们分类为父进程或子进程,因此由于 2 的 pid = 0并且 2 的 pid != 0,2 将被报告为 parent ,2 将被报告为 child 。

P1 pid != 0 (classify parent)
P2 pid != 0 (classify parent)
P3 pid == 0 (classify child)
P4 pid == 0 (classify child)

的确,P1先于P2创建,先于P3先于P4创建,但是它们何时进入switch语句以及何时打印它们的消息是由调度程序控制的。考虑创建流程需要花费大量时间(不仅仅是打印内容)的可能性。所以 P1 创建 P2,然后转身创建 P3,同时 P2 忙于创建 P4。 P3 被创建并打印东西,而 P2 仍然停留在创建 P4 上。

关于linux - 在程序中使用fork时执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21320746/

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