bash 检查进程并在未找到时重新启动程序的脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18790421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 06:33:11  来源:igfitidea点击:

Script to check for process & restart program if not found

linuxbashprocess

提问by linuxnoob

I am using this check script to see if a package called CCcam is running & restart it if it is not..

我正在使用此检查脚本来查看名为 CCcam 的包是否正在运行,如果不是,请重新启动它。

#!/bin/sh 
process=`ps auxwww | grep CCcam | grep -v grep | awk '{print }'`
if [ -z "$process" ]; then
echo "Couldn't find CCcam running. Restarting server-binary" >> /var/cccamlog/cccam.check 
echo && date >>/var/cccamlog/cccam.check
/usr/local/bin/CCcam -d >> /var/cccamlog/CCcam.log & 
else echo "CCcam is still OK!" >> /var/cccamlog/cccam.check 
fi 

The script is reporting "CCcam is still OK!"

脚本报告“CCcam 仍然正常!”

But it is not running, If i search for the process using this command: ps x |grep -v grep |grep -c CCcam, I get 0 so I know the process is not running.

但它没有运行,如果我使用这个命令搜索进程: ps x |grep -v grep |grep -c CCcam,我得到 0 所以我知道进程没有运行。

Is there any other factors that I should take into account that might be fooling the check script into thinking CCcam is running? For example, could there be some kind of tag left after the program crashes/stops that the script is picking up on?

是否有任何其他因素我应该考虑到可能会欺骗检查脚本认为 CCcam 正在运行?例如,在程序崩溃/停止后,脚本是否会留下某种标记?

From another test I get.. ERROR: CCcam still runs with pid:

从另一个测试我得到..错误:CCcam 仍然使用 pid 运行:

回答by Aleks-Daniel Jakimenko-A.

if pidof -s CCCam > /dev/null; then
    echo 'It is already running!'
else
    echo 'process not found...'
fi

回答by iamauser

You can also use pgrepin this case. It looks for the process name CCCam in proc table.

您也可以pgrep在这种情况下使用。它在 proc 表中查找进程名称 CCCam。

if [[ $(pgrep CCCam) ]]; then
   echo "CCCam is running";
else
   echo "Not Running, so I must do something";
   # DO something ....
fi