0

我需要从代码中打印进程树的帮助。感谢 stackoverflow 社区,我编写了一个程序,它使用 fork() 函数创建了几个进程,现在我需要使用 execlp() 函数在屏幕上打印一个进程树。

int main()
{
    int t = 5;
    int mainPID = getpid();
    cout << "Main process: " << mainPID << endl << endl;

    int pid;
    if ((pid = fork()) == -1) return -1;
    if (pid == 0)
    {
        cout << "source for child process ";
    }
    else{
        cout << "source for parent process ";
    }
    sleep(t);
    return 0;
}

当我运行程序和终端类型的另一个实例时

pstree /mainPID/ 

我得到从 mainPID 开始打印的树。我需要从代码中打印那棵树,但是当输入代码时

execlp("pstree", "pstree", "-c", "-p", (int *)NULL);

我从所有系统中获取打印树

execlp("pstree", "pstree", mainPID, "-c", "-p", (int *)NULL);

什么都不打印。

4

2 回答 2

0

execlp 将 char *const argv[] 作为其余参数...

所以尝试将“mainPID”转换为 char[]

这在我的情况下有效。

于 2019-12-01T18:23:00.107 回答
-1

你应该将 mainPID 转换为 string 或 char * 然后试试这个。

于 2019-11-22T16:23:06.370 回答