引言
程序是由代码形成的,代码是由人写的。只要是人,都会有疏忽的时候,导致写出的程序有bug,当然最严重的bug就是程序闪退。
本文旨在提供一个程序守护脚本,当监测到程序闪退后,立马将程序再起启动!
脚本
#!/bin/bashsleep 10 while true;
dovariable=`ps aux | grep helloworld | grep -v grep` # helloworld 是程序名字if [ ! "$variable" ]; thencd /home/ygt/test/nohup ./helloworld &echo 'restart helloworld at time' >> restart_log.txtecho $(date +%F%n%T) >> restart_log.txtfisleep 10 # 每10秒监测一次
done
知识点
ps
是一个显示当前进程的快照的工具。a
选项表示显示所有用户的进程。u
选项表示显示用户/所有者信息。x
选项表示不仅显示终端的进程,也显示没有控制终端的进程。- variable 是一个变量,执行
ps aux | grep helloworld | grep -v grep
命令,并将输出赋值给变量variable。使用:$(
variable)。
ps aux
的输出通常包含多列,如用户ID、进程ID、CPU使用率、内存使用率、启动时间、命令行等。
grep
是一个用于文本搜索的工具。-v
选项表示反转搜索的结果,即显示不包含指定模式的行。
grep -v grep
用于排除由第一个grep
命令产生的进程。因为搜索helloworld
时,grep helloworld
这个命令本身也会作为一个进程出现在ps aux
的输出中,而如果不希望看到这个进程。所以,使用grep -v grep
来排除它。
if [ ! "$
variable" ]; then ... fi
:这是一个if
语句,用于检查$
variable 变量是否为空(即helloworld
进程是否没有运行)。如果为空(即没有找到该进程),则执行then
和fi
之间的代码块。
nohup ./
helloworld
&
:在后台使用nohup
命令启动helloworld
进程,即使退出了shell终端,这个进程也会继续运行。