Shell-Script
如何獲取 cron 腳本的 pid?
我正在使用centOS 7,並且正在嘗試將這些walktroughs一起製作:
儘管如此,兩者看起來都非常聰明,當我嘗試手動檢查第一個腳本時,我遇到了困難。
因此,在 /etc/cron.hourly 中,我使用以下腳本放置了 sidekiq_restart:
#!/bin/bash # A simple script to check if a process is running and if not will # restart the process and send a mail. ################################################ # The name of the program we want to check PROGRAM=sidekiq # The user we would like notified of the restart MAILUSER="someone@weeenospam.blah" ################################################ PROCESSPID=$(pidof -s $PROGRAM) if [ -z "$PROCESSPID" ]; then # Use systemctl systemctl stop $PROGRAM.service systemctl start $PROGRAM.service # Comment above and uncomment below to use service rather than systemctl # service $PROGRAM restart echo mail -s "Service $PROGRAM was found to be stopped on $HOSTNAME at $(date) and has been restarted" $MAILUSER << /dev/null echo "$PROGRAM had FAILED on $HOSTNAME @ $(date)" >> $PROGRAM-check.log else echo "$PROGRAM was running ok on $HOSTNAME @ $(date)" >> $PROGRAM-check.log fi exit
我將 sidekiq 作為服務執行:
systemctl start sidekiq
當我檢查時
ps -aux | grep [s]idekiq
:deploy_+ 9883 36.4 0.6 474972 100292 ? Ssl 14:23 0:02 sidekiq 5.1.3 pnvstart [0 of 20 busy]
看起來很完美!但是當我嘗試時:
pidof -s sidekiq
它什麼也沒返回!當然這意味著腳本會出錯!如何解決?提前致謝!
從您的
ps
輸出來看,它看起來像是sidekiq
更改了自己的程序名稱以包含執行時資訊:sidekiq 5.1.3 pnvstart [0 of 20 busy]
. 在這種情況下,pidof
可能找不到它,因為它正在尋找“sidekiq”。如果您不打算手動啟動和停止 sidekiq,您可以使用 systemd 自己的工具:
systemctl is-active sidekiq
如果 sidekiq 未執行,將返回錯誤程式碼,如果執行則成功。就個人而言,我是 exit-soon 的朋友,所以我會按照以下方式編寫程式碼
systemctl is-active sidekiq && exit # all is well # oh no, it's gone! systemctl restart sidekiq mail -s ...