我正在尝试每隔10分钟检查一个进程是否正在运行,如果没有,请重新启动该进程。我希望这个脚本在系统启动时自动启动,所以我选择services in Linux
下面是我所做的:
作为服务编写bash脚本。
在壳的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

最佳答案

在后台执行函数。说:

start)
      start &

而不是说:
start)
      start

关于linux - 如何在启动方法中启动包含无限循环的Linux服务(Bash脚本),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19954067/

10-11 22:05
查看更多