【发布时间】:2013-11-13 12:41:01
【问题描述】:
我正在尝试每 10 分钟检查一次我的某个进程是否正在运行,如果没有,请重新启动该进程。我希望这个脚本在系统启动时自动启动,所以我选择services in Linux。
这就是我所做的:
- 将 Bash 脚本编写为服务。
- 在shell的
start方法中 脚本,在无限循环中,检查是否存在临时文件。 如果可用,请按照我的逻辑,否则打破循环。 - 在
stop方法中, 删除临时文件。 - 然后我使用 update-rc.d 将此脚本添加到 系统启动。
一切正常,除了一件事。如果我执行./myservice start,那么终端会挂起(它应该运行一个无限循环),但如果我执行ctrl-z,那么脚本将被终止,我的任务将无法执行。如何使此脚本从终端启动并正常执行? (例如,./etc/init.d/mysql start)。也许在后台执行该过程并返回。
我的 Bash 脚本如下:
#!/bin/bash
# Start the service
start() {
#Process name that need to be monitored
process_name="mysqld"
#Restart command for process
restart_process_command="service mysql start"
#path to pgrep command
PGREP="/usr/bin/pgrep"
#Initially, on startup do create a testfile to indicate that the process
#need to be monitored. If you dont want the process to be monitored, then
#delete this file or stop this service
touch /tmp/testfile
while true;
do
if [ ! -f /tmp/testfile ]; then
break
fi
$PGREP ${process_name}
if [ $? -ne 0 ] # if <process> not running
then
# restart <process>
$restart_process_command
fi
#Change the time for monitoring process here (in secs)
sleep 1000
done
}
stop() {
echo "Stopping the service"
rm -rf /tmp/testfile
}
### main logic ###
case "$1" in
start)
start
;;
stop)
stop
;;
status)
;;
restart|reload|condrestart)
stop
start
;;
*)
echo $"Usage: $0 {start|stop|restart|reload|status}"
exit 1
esac
exit 0
【问题讨论】:
-
脚本没有被杀死,它只是被挂起。输入
bg将在后台恢复它。