【发布时间】:2021-04-06 22:37:58
【问题描述】:
首先,我是 Linux 和进程的新手,所以我无法准确理解 fork() 的逻辑。我想从用户输入创建一个进程树并使用“pstree”显示这个树。但是,我的代码不止一次显示树。我认为原因是 fork() 复制了“pstree”命令,我无法解决这个问题。代码是这样的:
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string>
#include<sys/types.h>
#include<sys/wait.h>
using namespace std;
int main(int argc, char* argv[])
{
int forkSize, currentPid,b=0;
forkSize=atoi(argv[1]);
int parentPid=getpid();
for(int i=0;i<forkSize;i++)
{
currentPid = fork();
if (currentPid<0)
{
cout<<"Error in fork"<<endl;
exit(0);
}
if(currentPid == 0)
{
cout << "Child process: My parent id = " << getppid() << endl;
cout << "Child process: My process id = " << getpid() << endl;
}
else
{
cout << "Parent process. My process id = " << getpid() << endl;
cout << "Parent process. Value returned by fork() = " << currentPid << endl;
}
}
fflush(stdout);
char mychar[500];
sprintf(mychar, "pstree -p -U %d", parentPid);
system(mychar);
fflush(stdout);
cout<<endl;
return 0;
}
当我使用输入 4 尝试此代码时,输出如下所示:
我不明白为什么它会一次又一次地显示所有内容。有没有办法一次显示树?如果能帮助我,我会很高兴的。
【问题讨论】:
-
你的分叉创建了多个进程,每个进程都将继续运行命令。如果您不希望他们这样做,您应该让子进程在它们开始调用命令之前退出。
-
你还应该让子进程休眠几秒钟,这样当父进程运行
pstree时它们仍然会在那里。 -
@thatotherguy 我想他想让孩子分叉更多的孩子,这样他就可以看到所有进程的大树。所以他们不能立即退出。
-
@thatotherguy - 如何在调用命令之前退出?我试图退出 'if(currentPid==0)' 部分,但它没有显示我想要的树。也许我理解错了。正如我所说,我是这个领域的新手,我的头脑非常混乱。对此我很抱歉。