在我們的應用程式中,我們啟動一些後台進程。這些進程的 pid 被儲存到一個檔案中。
當達到最大值或系統重新啟動時,將重新使用 pids 值。
如何可靠地檢查 pid X 的進程是否仍是儲存 X 的進程。
我讀了 https://serverfault.com/questions/366474/whats-a-proper-way-of-checking-if-a-pid-is-running 和https://stackoverflow.com/questions/3043978/how-to-check-if-a-process-id-pid-exists 但這些解決方案從不檢查具有 pid X 的進程是否與儲存 pid 的進程仍然是相同進程。
我需要這些資訊才能可靠地
- 檢查進程仍在運行
- 殺死該進程,而不必冒殺死現在具有 pid X 的不同進程的風險
有關的https://serverfault.com/questions/279178/what-is-the-range-of-a-pid-on-linux-and-solaris
我將發布我目前的解決方案。我想知道這是否是一種明智的方法以及是否有更好的方法來做到這一點。
答案1
我為此創建了以下解決方案
我的啟動腳本包含
nohup $commandline >> $TEMP/logfile 2>&1 &
MYPID=$!
echo $MYPID > pidfile
cat /proc/$MYPID/cmdline >> pidfile
我的停止腳本讀取 pidfile 並檢查 cmdline 是否與最初保存的對應
[ -f pidfile ] || { echo no pidfile; exit 1; }
read pid < pidfile
psatstart=$(tail -1 pidfile)
psnow=$(</proc/$pid/cmdline)
if [[ "$psnow" == "$psatstart" ]]
then
echo kill $pid
kill $pid || { echo kill $pid failed; exit 2; }
while ps -p $pid
do
sleep 1
done
else
echo pid $pid not the same, assume already ended
echo S $psatstart
echo N $psnow
fi
rm pidfile