萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux 快速查詢進程 PID:pgrep 命令詳解

告別 ps aux | grep xxx 的繁瑣管道,pgrep 專為「按名稱搜尋進程 PID」而生,輸出乾淨、速度快,是運維日常必備指令。

基本用法

pgrep [-l] 關鍵字

參數說明

  • -l:同時顯示 PID 與進程名(強烈建議加上,否則只看到一串數字難以辨識)
  • 不加參數:僅輸出 PID 列表

實戰對比

# 僅顯示 PID
# pgrep httpd
2092
2094
2096
2098
2106
2108
2109
2111
14705

# 顯示 PID + 進程名(推薦)
# pgrep -l httpd
2092 httpd
2094 httpd
2096 httpd
2098 httpd
2106 httpd
2108 httpd
2109 httpd
2111 httpd
14705 httpd

進階技巧

  • pgrep -u root httpd:僅列出 root 用戶啟動的 httpd 進程
  • pgrep -f pattern:匹配完整命令行(含參數),而非僅進程名
  • pgrep -n/-o pattern:最新/最舊啟動的進程
  • pkill pattern:直接發送信號終止匹配進程(等同 kill $(pgrep pattern))

適用場景

  • 腳本中快速獲取主進程 PID
  • 配合 kill 批量重啟服務
  • 監控系統檢查關鍵進程存活

小結: pgrep 雖功能單一,但解決「按名找 PID」這一高頻需求極其高效,建議養成 pgrep -l 的肌肉記憶。

copyright © 萬盛學電腦網 all rights reserved