首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++ fork() -如何使用fork和pstree显示进程树?

C++ fork() -如何使用fork和pstree显示进程树?
EN

Stack Overflow用户
提问于 2021-04-07 06:37:58
回答 1查看 279关注 0票数 0

首先,我不熟悉Linux和进程,所以我不能准确地理解fork()的逻辑。我想从用户输入创建一个进程树,并使用'pstree‘显示此树。但是,我的代码不止一次地显示树。我想原因是fork()复制了'pstree‘命令,我不能解决这个问题。代码是这样的:

代码语言:javascript
复制
#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尝试此代码时,输出如下所示:

output

我不明白为什么它会一遍又一遍地显示所有内容。有没有办法只显示一次树?如果能帮到我,我会很高兴的。

EN

回答 1

Stack Overflow用户

发布于 2021-04-07 07:01:19

所有进程最终都会得到运行pstree的代码。您应该在那里检查您是否在原始的父进程中,并且只在这种情况下运行pstree

代码语言:javascript
复制
#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++。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66977343

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档