Linux 如何通过`pstree`获取所有父进程和所有子进程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12852023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:35:39  来源:igfitidea点击:

how to get all parent processes and all subprocesses by `pstree`

linuxshellcommand-line

提问by Congbin Guo

command pstree PIDcan show all subprocess information of the process specified by PID. However, I also want to know all parent process information of the process PID, how can I get it?

命令pstree PID可以显示指定进程的所有子进程信息PID。但是,我也想知道进程的所有父进程信息PID,如何获取?

An example, give below process:

一个例子,给出以下过程:

init
|- parent_process
|    `- current_process
|       |- subprocess_1
|       `- subprocess_2
`- other_process

What I want is when I run pstree current_process_pid, I want to get below output

我想要的是当我运行时pstree current_process_pid,我想要低于输出

init
`- parent_process
    `- current_process
       |- subprocess_1
       `- subprocess_2

When I run pstree subprocess_1_pid, it will output

当我运行时pstree subprocess_1_pid,它会输出

init
`- parent_process
    `- current_process
       `- subprocess_1

Thanks in advance

提前致谢

回答by MeaCulpa

# With my psmisc 22.20:
pstree -p -s PID

Maybe if with ps -ef:

也许如果使用 ps -ef:

awk -vPID= '
function getParent ( pid ) {
    if (pid == "" || pid == "0") return;
    while ("ps -ef | grep "pid | getline) {
        if ( == pid) {
            print "("") Called By ";
            getParent();
            break;
        }
    }
    close ("ps -ef")
}

BEGIN { getParent(PID) }
'

This is ugly assuming ps output column and order. Actually one single run of ps -ef contains all info needed. This don't worth the time, I still recommend updating psmisc, it won't hurt.

假设 ps 输出列和顺序,这很难看。实际上,一次运行 ps -ef 就包含了所有需要的信息。这不值得花时间,我仍然建议更新 psmisc,它不会受到伤害。

EDIT: A mimic using single run ps -ef:

编辑:使用单次运行 ps -ef 的模拟:

ps -ef | awk -vPID= '
function getpp ( pid, pcmd, proc ) {
    for ( p in pcmd ) {
        if (p == pid) {
            getpp(proc[p], pcmd, proc);
            if (pid != PID) printf("%s(%s)───", pcmd[pid], pid);
        }
    }
}

NR > 1 {
    # pid=>cmd
    pcmd[] = ;
    # pid=>Parent
    pproc[] = ;
}

END {
    getpp(PID, pcmd, pproc);
    printf "\n";
    system("pstree -p "PID);
}'

回答by martemiev

I found lapsoptions mentioned by @haridsv (pstree -laps <pid>) being a solution. It was a bit verbose for me though, so I'd stick to a shorter apsoutput.

我发现laps@haridsv ( pstree -laps <pid>)提到的选项是一个解决方案。不过对我来说有点冗长,所以我会坚持使用较短的aps输出。