17

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

一个例子:

在里面
|- 父进程
| `- current_process
| |- 子进程_1
| `- subprocess_2
`- 其他进程

我想要的是当我运行时pstree current_process_pid,我想得到以下输出:

在里面
`- 父进程
    `- current_process
       |- 子进程_1
       `- subprocess_2

当我运行pstree subprocess_1_pid时,它将输出:

在里面
`- 父进程
    `- current_process
       `- subprocess_1
4

2 回答 2

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

也许如果使用 ps -ef:

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

BEGIN { getParent(PID) }
'

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

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

ps -ef | awk -vPID=$1 '
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[$2] = $8;
    # pid=>Parent
    pproc[$2] = $3;
}

END {
    getpp(PID, pcmd, pproc);
    printf "\n";
    system("pstree -p "PID);
}'
于 2012-10-12T05:03:32.363 回答
7

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

获取当前进程的进程树(其 ID$$在 Bash 中):

pstree -aps $$

像这样打印进程树:

systemd,1
  └─kitty,86739
      └─bash,86742
          └─pstree,86904 -aps 86742
于 2017-03-27T11:40:27.813 回答