我是Fedora的新手,只是使用c ++代码在Fedora中创建进程。我想从父进程制作 2 个进程。我在我的代码中这样做,但是当创建进程 2 并且我检查其父 ID 时,它与原始父 Id 不同,可以说出为什么这段代码显示这种行为谢谢。
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <spawn.h>
#include <unistd.h>
#include <sys/wait.h>
using namespace std;
int main()
{
cout<<"Begning of the program"<<endl;
int counter=0;
pid_t child1=fork();
if(child1==0)
{
cout<<"Child1 Process"<<endl;
cout<<"Process ID: "<<getpid()<<endl;
cout<<"Parrent ID: "<<getppid()<<endl;
}
else if(child1>0)
{
pid_t child2=fork();
if(child2>0)
{
cout<<"Parrent of Child1 and Child2"<<endl;
cout<<"Process ID: "<<getpid()<<endl;
cout<<"Parrent ID: "<<getppid()<<endl;
}
else if(child2==0)
{
cout<<"Child2 Creadted"<<endl;
cout<<"Process ID: "<<getpid()<<endl;
cout<<"Parrent ID: "<<getppid()<<endl;
}
else
{
cout<<"Process Failed"<<endl;
}
}
else
{
cout<<"Process fail"<<endl;
}
cout<<"End "<<endl;
return 0;
}
结果:
Begning of the program
Parrent of Child1 and Child2
Child1 Process
Process ID: 2186
Parrent ID: 2059
End
Process ID: 2187
Parrent ID: 2186
End
Child2 Creadted
Process ID: 2188
Parrent ID: 1287
End
在分叉子进程输出其父进程 ID 之前,真正的父进程(调用fork()
(已经退出。子进程重新附加到组父进程,该 pid 由子进程输出。
您可以调用pstree -p
以查看哪个进程是 1303。
我建议更换线路
cout<<"Process ID: "<<getpid()<<endl;
cout<<"Parrent ID: "<<getppid()<<endl;
跟
cout << getpid() << ": Parent ID: "<< getpid() << endl;
这将有助于分离可能的混合输出(因为输出顺序未确定(。示例输出:
2186: Parent ID: 2059
在创建进程 2 后应用 wait,就像我在代码中所做的那样。以便父级保持活动状态,直到子项 2 执行。在你是代码中,父级在创建子 2 后死亡,这使得子项 2 成为僵尸进程。
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <spawn.h>
#include <unistd.h>
#include <sys/wait.h>
using namespace std;
int main()
{
cout<<"Begning of the program"<<endl;
int counter=0;
pid_t child1=fork();
if(child1==0)
{
cout<<"Child1 Process"<<endl;
cout<<"Process ID: "<<getpid()<<endl;
cout<<"Parrent ID: "<<getppid()<<endl;
}
else if(child1>0)
{
pid_t child2=fork();
wait(NULL);
if(child2>0)
{
cout<<"Parrent of Child1 and Child2"<<endl;
cout<<"Process ID: "<<getpid()<<endl;
cout<<"Parrent ID: "<<getppid()<<endl;
}
else if(child2==0)
{
cout<<"Child2 Creadted"<<endl;
cout<<"Process ID: "<<getpid()<<endl;
cout<<"Parrent ID: "<<getppid()<<endl;
}
else
{
cout<<"Process Failed"<<endl;
}
}
else
{
cout<<"Process fail"<<endl;
}
cout<<"End "<<endl;
return 0;
}