
我有一個每隔幾週停止運行的二進位文件,您只需再次啟動它,它就會再運行幾週。軟體雖然不完美,但如果能自動重新啟動就夠完美了。
設定自動檢查二進位檔案是否正在運行並在沒有運行時啟動它的最佳方法是什麼?
答案1
控製程式的優雅方法是使用 PID 檔案機制建立腳本,它將程式的 PID 保存到檔案中,並檢查進程是否仍在運行:
#!/bin/bash
PID_FILE=/var/run/rerun.pid # need root permission to store in this directory
EXEC=/usr/bin/gedit # replace it with actual executable
function run() {
# execute the program
$EXEC &
# save its PID
echo $! > $PID_FILE
}
if [ -e $PID_FILE ]; then
# check if program is still running
pid=$(<$PID_FILE)
# find the proper process
ps --pid $pid|grep -q `basename $EXEC`
if [ $? != 0 ]; then
# not found - rerun
run
fi
else
# no PID file - just execute
run
fi
現在定期運行腳本(例如,在定時任務)。