初学者 Linux pstree 命令教程(8 个示例)
在此页
- Linux pstree 命令
- Q1。如何使用 pstree 命令?
- Q2。如何使 pstree 在输出中也包含命令行参数?
- Q3。如何强制 pstree 在输出中扩展相同的子树?
- Q4。如何让pstree 高亮某个特定的进程?
- Q5。如何让 pstree 在输出中显示进程组 ID?
- Q6。如何根据 PID 使 pstree 排序进程?
- Q7。如何使 pstree 显示特定于用户的进程树?
- Q8。如何限制Pstree到特定进程?
- 结论
由于 Linux 系统中的每个进程(第一个进程除外)都有一个父进程,因此如果所有进程都以树结构显示,有时会使事情更容易理解。您会很高兴知道存在一个命令行实用程序 - 称为 pstree - 可以显示进程树。
在本教程中,我们将使用一些易于理解的示例来讨论 pstree 命令的基础知识。但在我们这样做之前,值得一提的是,这里的所有示例都已经在 Ubuntu 22.04 LTS 机器上进行了测试。
Linux pstree 命令
如开头所述,pstree 命令显示进程树。以下是它的语法:
pstree [options]
下面是工具手册页关于它的内容:
pstree shows running processes as a tree. The tree is rooted at either
pid or init if pid is omitted. If a user name is specified, all
process trees rooted at processes owned by that user are shown.
pstree visually merges identical branches by putting them in square
brackets and prefixing them with the repetition count, e.g.
init-+-getty
|-getty
|-getty
`-getty
becomes
init---4*[getty]
Child threads of a process are found under the parent process and are
shown with the process name in curly braces, e.g.
icecast2---13*[{icecast2}]
If pstree is called as pstree.x11 then it will prompt the user at the
end of the line to press return and will not return until that has hap?
pened. This is useful for when pstree is run in a xterminal.
Certain kernel or mount parameters, such as the hidepid option for
procfs, will hide information for some processes. In these situations
pstree will attempt to build the tree without this information, showing
process names as question marks.
以下是一些 Q&A 风格的示例,应该可以让您对 pstree 命令的工作原理有一个很好的了解:
Q1。如何使用 pstree 命令?
基本用法很简单:您所要做的就是在没有任何选项的情况下执行 pstree。
pstree

所以你可以看到 pstree 是如何在输出中产生进程相关信息的。
Q2。如何使 pstree 在输出中也包含命令行参数?
这可以使用 -a 命令行选项来完成。
pstree -a

所以你可以看到 pstree 命令现在也显示一些进程的命令行选项。
Q3.如何强制 pstree 在输出中扩展相同的子树?
默认情况下,pstree 命令合并相同的分支,方法是将它们放在方括号中并在它们前面加上重复计数。像这样:

但是,如果需要,您可以强制该工具展开相同的树,您可以使用 -c 命令行选项执行此操作。
pstree -c

Q4.如何让pstree 高亮某个特定的进程?
如果您希望该工具在输出中突出显示特定进程,请使用 -H 命令行选项。
pstree -H [PID]
其中 PID 是您要突出显示的进程的 ID。例如,我使用以下命令在我的系统上突出显示了 firefox 进程:
pstree -H 3124

因此,您可以看到与其他名称相比,名称 firefox 略微突出显示。
Q5.如何让 pstree 在输出中显示进程组 ID?
为此,请使用 -g 命令行选项。
pstree -g

因此,您可以看到进程组 ID 在每个进程名称后的括号中显示为十进制数字。
Q6.如何根据 PID 使 pstree 排序进程?
默认情况下,pstree 按名称对具有相同祖先的进程进行排序。但是,如果您愿意,您也可以使用 PID 对进程进行 pstree 排序,这可以使用 -n 命令行选项来完成。
pstree -n
请注意,这种类型的排序也称为数字排序。
Q7.如何使 pstree 显示特定于用户的进程树?
如果您希望 pstree 显示以特定用户拥有的进程为根的所有进程树,那么您所要做的就是将该用户的名称作为输入传递给命令。
例如,
pstree himanshu
所以在这种情况下,我的系统产生了以下输出:

Q8.如何限制Pstree到特定进程?
如果您希望 pstree 仅显示特定进程的父子信息,请使用 -s 选项。
pstree -s [PID]
例如,我想将 Pstree 输出限制为我系统上的 firefox 进程,所以我执行了以下命令:
pstree -s 3124
这是工具显示的输出:

结论
根据您所做的工作类型,pstree 命令可能会有很大帮助。在本教程中,我们讨论了该工具提供的一些关键命令行选项。有关更多信息,请访问其手册页。