如何解决C++ fork() - 如何使用 fork 和 pstree 显示进程树?
首先,我是 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
的代码。您应该在那里检查您是否在原始父进程中,并且只在这种情况下运行 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;
sleep(1);
}
else
{
cout << "Parent process. My process id = " << getpid() << endl;
cout << "Parent process. Value returned by fork() = " << currentPid << endl;
}
}
if (getpid() == parentPid) {
char mychar[500];
sprintf(mychar,"pstree -p -U %d",parentPid);
system(mychar);
}
return 0;
}
顺便说一句,endl
刷新输出,您不需要调用 fflush(stdout);
。还有,那是 C,但你的代码是 C++。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。