nginx守护进程shell代码实现

vim nginx_daemon.sh

#!/bin/bash
#
# set password="XXX" # 预输入需要的密码
# echo $$, 直接输出执行脚本过程产生的子进程的PID
# 用来过滤脚本本身执行时启动子进程
# 常用于执行脚本传参为进程名称时,查看某个进程情况避免干扰
this_pid=$$
# 通过“grep -v $this_pid”直接把自身执行的子进程过滤掉,
# 这样就可以不管脚本中起的名字包含什么字眼,只要你执行这个脚本的时候过滤掉,
# 从而可以使判断进程是否存在的执行命令做出正确判断
while true
do
ps -ef | grep nginx | grep -v grep | grep -v $this_pid &>/tmp/null

if [ $? -eq 0 ];then
echo "Nginx is running well"
# 等待3s
sleep 3
else
# Mac 使用
# sudo nginx
# systemctl start nginx

#使用nginx自动命令/usr/sbin/nginx启动 

/usr/sbin/nginx
echo "Nginx is down, Start it ..."
fi
done


# 脚本运行结果
~ % sh 27.nginx_daemon.sh
Nginx is running well
Nginx is running well
Nginx is down, Start it ...
Nginx is running well

使用nopub命令,让脚本运行日志不在前台输出并后台运行进程

# 通过nohup后台挂起运行程序,通过exit命令退出终端然后关闭shell,
# 注意:不能直接退出终端,要不后台无法挂起任务
# 直接输入以下命令,连续两次回车,进程开始在后台作为一个守护进程不停运行
~ % nohup nginx_daemon.sh &

[1] 36623
~ % appending output to nohup.out
~ %
# 查看守护进程的日志输出
~ % tail -f nohup.out
Nginx is running well
Nginx is running well
Nginx is down, Start it ...
Nginx is running well

# nohup关闭后台程序
# 方式一:通过jobs -l查看进程PID,kill命令结束进程,
# 用于查看当前终端后台运行的任务,换了终端就看不到了
~ % jobs -l
[1] + 36623 running nohup sh 27.nginx_daemon.sh
~ % kill % 36623
[1] + terminated nohup sh 7.nginx_daemon.sh
~ % jobs -l
# 方式二:通过ps -ef查看进程PID,kill命令结束进程,
# 用于查看瞬间进程动态,可以看到别的终端后台运行
~ % ps -ef | grep "27.nginx_daemon.sh" | grep -v grep
501 37561 36017 0 12:39上午 ttys000 0:00.01 sh 27.nginx_daemon.sh
~ % kill % 37561
[1] + terminated nohup sh 27.nginx_daemon.sh

posted @ 2022-06-08 19:35  谢端阳  阅读(284)  评论(0编辑  收藏  举报