每次执行程序时,内核都会创建一个与该程序相关联的进程。简单来说,进程是 Linux 中程序的运行实例。
内核创建的进程称为‘父进程‘。从父进程派生或生成的进程称为‘子进程‘。一个父进程可能包含多个子进程,每个子进程具有唯一的PID(进程ID),但共享相同的PPID。
在本指南中,我们将探讨各种方法,您可以使用这些方法来找出Linux系统上的父进程ID(PPID)或进程。
PID和PPID之间有什么区别?
A program that is loaded into memory and running is known as a process. Once started, the process is given a unique number known as the process ID (PID) that uniquely identifies it in the system. The process can be referred to at any time using its PID. For example, to kill a process, you will have to know its PID first.
除了PID之外,每个进程还被分配一个父进程ID(PPID),显示哪个进程生成了它。因此,PPID是进程的父进程的PID。
为了将这一点放入上下文中,假设具有PID的5050的进程5启动了进程6。进程6将被分配一个唯一的PID,例如6670,但仍将被赋予PPID的5050。
这里的父进程是进程5,子进程是6。子进程被分配了一个唯一的PID,但PPID与父进程(进程5)的PID相同
A single parent can start multiple several child processes, each with a unique PID but all sharing the same PPID.
在Linux中查找父进程ID(PPID)
在Linux系统上查找运行进程的PPID有两个主要方法:
- 使用pstree命令。
- 使用ps命令和
通过pstree命令查找Linux进程的PPID
A pstree command is a command-line tool that displays running processes as a tree, which makes for a convenient way of displaying processes in a hierarchy. It shows the parent-child relationship in a tree hierarchy.
。使用 -p
选项,pstree命令显示所有运行的父进程以及它们对应的子进程和各自的PID。
$ pstree -p

从输出中,我们可以看到父进程ID和子进程ID。
为了演示,我们将检查PPID为Mozilla Firefox的整个进程层次结构,使用以下命令:
$ pstree -p | grep 'firefox'

从输出中,您可以看到PPID的Firefox是3457,其余的是PIDs的子进程。
要仅显示Firefox的PPID并跳过其余的输出,将输出通过管道传递给head命令,并使用-1
显示第一行。
$ pstree -p | grep 'firefox' | head -1

使用ps命令查找Linux进程的PPID。
另一种查找进程的PPID的方法是使用ps命令,这是一个广泛使用的命令,用于显示Linux系统上当前运行的进程。
当与-ef
选项一起使用时,ps命令会列出所有正在运行的进程及其详细信息,如UID、PID、PPID等。
$ ps -ef

为了缩小范围并显示特定进程的PPID,例如Firefox,可以通过-e
选项并将输出通过管道传递给grep命令,如下所示。
$ ps -e | grep 'firefox'

再次从输出中,您可以看到Firefox的PPID是3457。
在本指南中,我们展示了如何在Linux系统上查找正在运行的进程的PPIDs。您可以使用pstree命令或ps命令来达到相同的目的。