如何获取 cron 脚本的 pid?

如何获取 cron 脚本的 pid?

我正在使用 centOS 7,我正在尝试将这些演练组合在一起:

检查进程是否正在运行的脚本

Github 让 sidekiq 作为服务运行的示例

尽管如此,两者看起来都非常聪明,当我尝试手动检查第一个脚本时,我陷入了困境。

因此,在 /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="[email protected]"
################################################

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

它什么也没返回!当然,这意味着脚本将是错误的!如何解决这个问题?提前致谢!

答案1

从您的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 ...

相关内容