适用于 Linux 的 Solaris ptree 样式工具

Eld*_*dar 8 linux ps

我正在寻找将打印与 Solaris ptree 相同的输出的 Linux 工具。例如:

# ptree 538
538   /usr/lib/ssh/sshd
  889   /usr/lib/ssh/sshd
    890   /usr/lib/ssh/sshd
      1498  -sh
        1649  bash
          1656  -sh
            1660  bash
              13716 ptree 538
Run Code Online (Sandbox Code Playgroud)

我知道 pstree 存在,但我不喜欢它的输出格式。有人知道类似的工具吗?

Mik*_*ike 7

这就是我所知道的最像 linux 中的 ptree

ps -ejH
Run Code Online (Sandbox Code Playgroud)

  • 或`ps axf`。我觉得它更具可读性。 (3认同)

Gil*_*il' 6

这是一个显示类似于 Solaris pstree输出的脚本。不支持选项,不支持用户匹配。此脚本应可移植到所有 POSIX 系统。在某些ps命令不符合 POSIX 标准的系统上,您可能需要调整传递给ps. 该脚本包含对 BSD 系统的特定支持,因此应该涵盖大多数平台。

#! /bin/sh
## Usage: $0 [PID...]
## Show the processes on the system. For each process, show the process
## id followed by the command line. Show child processes after their parent,
## indented.
## If one or more PIDs are specified, only show the ancestors and
## descendants of those PIDs. If no PID is specified, show the subtree
## rooted at PID 1.
## This utility mimics Solaris pstree(1).
case $(uname) in *BSD*) ps_A='-ax';; *) ps_A='-A';; esac
ps $ps_A -o pid= -o ppid= -o args= |
sort -k 1n |
awk -v targets="$*" '
# children[p]: the " "-separated list of the pids of the children of p
# cmd[p]: command line of p
# list[lb..le]: list of pids yet to traverse
# depth[p]: depth of process p: depth(child) = depth(parent) + 1
# parent[p]: pid of the parent of p
# show[p]: 1 to show p, 2 to show p and all its descendants
BEGIN {
    list[0] = 0; lb = 0; le = 0;
    depth[0] = -1;
}
{
    pid=$1; ppid=$2;
    sub(/^ *[0-9]+ +[0-9]+ /, "");
    if (pid == ppid) {
        # This process is a root: add it to the list of processes to taverse
        list[++le] = pid;
    } else {
        children[ppid] = children[ppid] " " pid;
        parent[pid] = ppid;
    }
    cmd[pid] = $0;
}
END {
    # Parse targets into a list of pids (or 1 if none is specified).
    split("_" targets, a, /[^0-9]+/);
    delete a[1];
    if (a[2] == "") a[2] = 1;
    for (i in a) {
        show[a[i]] = 2; # Show targets recursively
        p = parent[a[i]];
        # Show target ancestors
        while (p && !show[p]) {
            show[p] = 1; 
            p = parent[p];
        }
    }

    # Traverse the list of processes
    while (lb <= le) {
        pid = list[lb++];
        # Add children to the list of processes to traverse
        split(children[pid], a);
        for (i in a) {
            list[--lb] = a[i];
            depth[a[i]] = depth[pid] + 1;
            if (show[pid] > 1) show[a[i]] = show[pid];
        }
        # Show the current process if desired, indenting to the right depth
        if (show[pid]) {
            for (i = 1; i <= depth[pid]; i++) printf("  ");
            printf("%-5d ", pid);
            print cmd[pid];
        }
    }
}
'
Run Code Online (Sandbox Code Playgroud)