http://weyo.me/pages/techs/linux-get-pid/
Date?2014-05-22????Category?Techs????Tags?Linux?/?Shell?
Posted by?WeYo. 轉(zhuǎn)載請注明出處:http://weyo.me/pages/techs/linux-get-pid/
導讀
Linux 的交互式 Shell 與 Shell 腳本存在一定的差異,主要是由于后者存在一個獨立的運行進程播玖,因此在獲取進程 pid 上二者也有所區(qū)別指巡。
交互式 Bash Shell 獲取進程 pid
在已知進程名(name)的前提下烤黍,交互式 Shell 獲取進程 pid 有很多種方法颗胡,典型的通過 grep 獲取 pid 的方法為(這里添加?-v grep是為了避免匹配到 grep 進程):
ps -ef | grep "name" | grep -v grep | awk '{print $2}'
或者不使用?grep(這里名稱首字母加[]的目的是為了避免匹配到 awk 自身的進程):
ps -ef | awk '/[n]ame/{print $2}'
如果只使用 x 參數(shù)的話則 pid 應(yīng)該位于第一位:
ps x | awk '/[n]ame/{print $1}'
最簡單的方法是使用?pgrep:
pgrep -f name
如果需要查找到 pid 之后 kill 掉該進程凑耻,還可以使用?pkill:
pkill -f name
如果是可執(zhí)行程序的話舒憾,可以直接使用?pidof
pidof name
Bash Shell 腳本獲取進程 pid
根據(jù)進程名獲取進程 pid
在使用 Shell 腳本獲取進程 pid 時,如果直接使用上述命令香拉,會出現(xiàn)多個 pid 結(jié)果,例如:
1
2
3
4
5
#! /bin/bash# process-monitor.shprocess=$1pid=$(ps x|grep$process|grep -v grep|awk'{print $1}')echo$pid
執(zhí)行?process-monitor.sh?會出現(xiàn)多個結(jié)果:
$> sh process-monitor.sh3036? 3098? 3099
進一步排查可以發(fā)現(xiàn)中狂,多出來的幾個進程實際上是子 Shell 的(臨時)進程:
root? ? ? 3036? 2905? 0 09:03 pts/1? ? 00:00:45 /usr/java/jdk1.7.0_71/bin/java ...nameroot? ? ? 4522? 2905? 0 16:12 pts/1? ? 00:00:00 sh process-monitor.sh nameroot? ? ? 4523? 4522? 0 16:12 pts/1? ? 00:00:00 sh process-monitor.sh name
其中 3036 是需要查找的進程pid凫碌,而 4522、4523 就是子 Shell 的 pid胃榕。 為了避免這種情況盛险,需要進一步明確查找條件,考慮到所要查找的是 Java 程序勋又,就可以通過 Java 的關(guān)鍵字進行匹配:
1
2
3
4
5
#! /bin/bash# process-monitor.shprocess=$1pid=$(ps -ef|grep$process|grep'/bin/java'|grep -v grep|awk'{print $2}')echo$pid
獲取 Shell 腳本自身進程 pid
這里涉及兩個指令: 1.?$$?:當前 Shell 進程的 pid 2.?$!?:上一個后臺進程的 pid 可以使用這兩個指令來獲取相應(yīng)的進程 pid苦掘。例如,如果需要獲取某個正在執(zhí)行的進程的 pid(并寫入指定的文件):
myCommand && pid=$!myCommand & echo $! >/path/to/pid.file
注意楔壤,在腳本中執(zhí)行?$!?只會顯示子 Shell 的后臺進程 pid鹤啡,如果子 Shell 先前沒有啟動后臺進程,則沒有輸出蹲嚣。
查看指定進程是否存在
在獲取到 pid 之后递瑰,還可以根據(jù) pid 查看對應(yīng)的進程是否存在(運行),這個方法也可以用于 kill 指定的進程隙畜。
if ps -p $PID > /dev/nullthen? echo "$PID is running"? # Do something knowing the pid exists, i.e. the process with $PID is runningfi