Pid

從 lsof 列表中獲取 PID

  • June 23, 2021

我有一個 react-native 應用程序,我想為啟動測試版本編寫一個腳本。如果它還活著,我需要擊落 :8081 埠。命令:

lsof -i :8081
kill -9 <PID>

得到這個結果的 lsof :

   COMMAND     PID USER   FD   TYPE   DEVICE SIZE/OFF NODE NAME
chrome     2423 loow  127u  IPv4 13749099      0t0  TCP localhost.localdomain:36650->localhost.localdomain:tproxy (ESTABLISHED)
qemu-syst 15091 loow   64u  IPv4 13795587      0t0  TCP localhost.localdomain:43518->localhost.localdomain:tproxy (ESTABLISHED)
qemu-syst 15091 loow   66u  IPv4 13795588      0t0  TCP localhost.localdomain:43520->localhost.localdomain:tproxy (ESTABLISHED)
qemu-syst 15091 loow   89u  IPv4 13777485      0t0  TCP localhost.localdomain:40500->localhost.localdomain:tproxy (ESTABLISHED)
node      16210 loow   16u  IPv6 13747716      0t0  TCP *:tproxy (LISTEN)
node      16210 loow   18u  IPv6 13751322      0t0  TCP localhost.localdomain:tproxy->localhost.localdomain:36650 (ESTABLISHED)
node      16210 loow   19u  IPv6 13798473      0t0  TCP localhost.localdomain:tproxy->localhost.localdomain:43518 (ESTABLISHED)
node      16210 loow   21u  IPv6 13798475      0t0  TCP localhost.localdomain:tproxy->localhost.localdomain:43520 (ESTABLISHED)
node      16210 loow   27u  IPv6 13777958      0t0  TCP localhost.localdomain:tproxy->localhost.localdomain:40500 (ESTABLISHED)

在這種情況下,我需要的是節點服務的 pid 16210。如何從 lsof 獲取它?

lsof -ti :8081嘗試了僅返回pid,但它返回了所有這些。我試圖用 grep: 擴展它lsof -ti :8081 | grep node,它什麼都不返回。

所以我只需要程序 id 就可以將其放入kill -9 $PID.

我認為您的整個方法存在缺陷,您可能應該在 systemd 下執行您的服務(或將其包裝在記錄 PID 的 systemV 樣式的啟動-停止腳本中),這將大大簡化停止正確服務的過程。

或者,查找特定程序的正常工具是pgrep和相關的pkill,可讓您輕鬆殺死它們:

pkill -9 -u node  react-native-app-name

話雖如此,回答您的字面問題:通常,要停止的正確服務程序是在該 TCP 埠上提供偵聽器的服務程序,即限制您的lsof輸出-sTCP:LISTEN

lsof -i :8081 -sTCP:LISTEN |awk 'NR > 1 {print $2}'  |xargs kill -15

引用自:https://serverfault.com/questions/847096