2021年1月21日 星期四

bash tips - 使用部分執行檔名來發出終止程式指令 terminate processes by partial process name

在 Linux 系統中,時常會遇到需要終止執行中的程式,如果只有單一執行檔程式執行多個 Instances 時,可簡單使用下列指令例如:

killall <process name>

但若是有多個 prefix 相同的程式就要分別指定

killall test_a test_b test_c

為了方便使用,初步寫一版可使用部分執行檔來終止程式的腳本,下例腳本是使用以下 /bin/sh 測試:

  • busybox v1.31
  • dash 0.5.8-2.10

Script example


#!/bin/sh
pname="$1"
if [ "x$pname" = x ]; then
echo "syntax: <partial process name>"; exit 1 ; fi
ps -a | grep "$pname" | \
grep -v grep | \
sed -e "s/^[ ]*\([0-9][0-9]*\) .*$/\1/g" | \
while read pid ; do kill $pid ; echo "terminate $pid" ; done

 Test output

~$ sleep 86400 &
[1] 2824
~$ sleep 86402 &
[2] 2832
sh 加上 -x 可除錯執行


~$ sh -x terminate_pname.sh sleep
+ pname=sleep
+ [ xsleep = x ]
+ ps -a
+ grep sleep
+ grep -v grep
+ sed -e s/^[ ]*\([0-9][0-9]*\) .*$/\1/g
+ read pid
+ kill 2824
+ echo terminate 2824
terminate 2824
+ read pid
+ kill 2832
+ echo terminate 2832
terminate 2832
+ read pid
[1]- Terminated              sleep 86400
[2]+ Terminated              sleep 86402

參考文章


沒有留言: