我正在嘗試控制一個基於 python 的程式(它不會從控制台分離)
#!/bin/bash
user=nobody
pid=/var/run/xx.pid
name=xx
prog=/xx.py
case $1 in
start)
/sbin/start-stop-daemon --start -b --oknodo --user "$user" --name "$name" --pidfile "$pid" --startas "$prog" --chuid nobody -- --daemon
;;
stop)
/sbin/start-stop-daemon --stop --oknodo --user "$user" --name "$name" --pidfile "$pid" --retry=TERM/5/KILL/1
;;
restart)
;;
*)
;;
esac
開始部分工作正常。我可以看到腳本啟動並運行,但停止部分卻看不到。它只是說No xx found running; none killed.
所以我猜開頭部分有問題?
答案1
start-stop-daemon --start --pidfile "$pid"
除非指定--make-pidfile
( ) ,否則不會寫入 pid 檔案。-m
如果沒有--make-pidfile
它,則由啟動的程式來建立它。另外,為了--make-pidfile
正常運作,正在啟動的程序無法自行守護進程(透過 fork),因為這樣start-stop-daemon
就不知道應該在檔案中放入什麼 PID。
在您的使用場景中唯一要做的事情是,如果程式已經在運行,--pidfile "$pid"
它將導致無法啟動程式。start-stop-daemon
如果進程仍未停止,則傳遞給的所有條件start-stop-daemon --stop
都必須符合。意義$pid
必須是正在運行的進程,進程的 UID 必須匹配$user
,進程名稱 (arg0) 必須匹配$name
。
您可以透過以下方式確定 arg0 的值ps h -p $pid -o comm