如何在Linux中查找父進程PPID

每次執行程式時,內核都會創建與該程式相關聯的進程。簡單來說,進程是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之外,每個進程還被分配一個父進程IDPPID),顯示哪個進程產生了它。因此,PPID是進程的父進程的PID

為了將這一點放入上下文中,讓我們假設具有PID5050的進程5啟動了進程6。進程6將被分配一個唯一的PID,例如6670,但仍然會被給予PPID5050

這裡的父進程是進程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
Show Linux Running Processes in Tree Hierarchy

從輸出中,我們可以看到父進程ID以及子進程ID。

為了示範,我們將使用以下命令檢查PPID以及Mozilla Firefox的整個進程層次結構:

$ pstree -p | grep 'firefox'
Find the PPID of the Linux Process

從輸出中,您可以看到PPIDFirefox3457,其餘的是PIDs的子進程。

為了僅顯示Firefox的PPID並跳過其餘輸出,請將輸出通過管道傳遞給head命令並使用-1顯示第一行。

$ pstree -p | grep 'firefox' | head -1
Print PPID of Linux Process

使用ps命令查找Linux進程PPID

另一種查找進程的PPID的方法是使用ps命令,這是一個廣泛使用的命令,用於顯示Linux系統上當前運行的進程

當與-ef選項一起使用時,ps命令列出了所有運行的進程及其詳細信息,例如UIDPIDPPID等。

$ ps -ef
List Running Linux Processes with PID

要縮小範圍並顯示特定進程的PPID,例如Firefox,請傳遞-e選項並將輸出通過管道傳遞給grep命令,如圖所示。

$ ps -e | grep 'firefox'
Find Linux Process PID

再次從輸出中,您可以看到PPIDFirefox3457

在本指南中,我們展示了如何在Linux系統上查找運行進程的PPIDs。您可以使用pstree命令或ps命令來達到相同的目標。

Source:
https://www.tecmint.com/find-parent-process-ppid/