启动,停止和重新启动守护程序的shell脚本

在Linux中,我们可以使用service启动,停止和重新启动服务。
例如:

$sudo service mysql stop
$sudo service mysql start
$sudo service mysql restart

如果是一些自己开发的软件,或者从源代码安装的。

我们可以使用Bash脚本来自定义一个服务进程控制器。

我们使用“nohup”来启动守护进程程序并将其放到后台运行。
将进程ID输出到$PID_FILE_PATH,以便我们稍后可以停止控制。
如果找到PID_FILE_PATH,则使用“PS”命令在内存中搜索进程,如果找到进程运行,则退出BASH。

#!/bin/bash
# Function: to start, stop and restart the application.
# Usage: 
$./runner.sh stop yes
cat: runner.pid: No such file or directory
kill: usage: kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... or kill -l [sigspec]
Failed to stop yes.
$./runner.sh start yes
Succeeded to start yes.
nohup: appending output to 'nohup.out'
$./runner.sh restart yes
Succeeded to stop yes.
Succeeded to start yes.
nohup: appending output to 'nohup.out'
$./runner.sh stop yes
Succeeded to stop yes.
start|stop|restart application if [[ "$#" -lt 2 ]]; then echo "Usage: ##代码## start|stop|restart command" echo "$# parameters given." exit 1 fi PID_FILE_PATH="runner.pid" case "" in start) # Already running if [ -f ${PID_FILE_PATH} ]; then pid=$(cat ${PID_FILE_PATH}) if $(ps -p ${pid} > /dev/null); then echo "Already running [PID: ${pid}], you can stop it and retry." exit 1 fi fi nohup "" 2>&1 \ & echo $! > ${PID_FILE_PATH} if [ $? -eq 0 ]; then echo "Succeeded to start ." else echo "Failed to start ." exit 1 fi ;; stop) kill $(cat ${PID_FILE_PATH}) if [ $? -eq 0 ]; then rm ${PID_FILE_PATH} echo "Succeeded to stop ." else echo "Failed to stop ." exit 1 fi ;; restart) ##代码## stop "" && sleep 1 && ##代码## start "" ;; esac

例子:

##代码##
日期:2020-07-07 20:54:33 来源:oir作者:oir