说明
php脚本以守护进程的方式,shell脚本监控php脚本是否工作,若php脚本未工作,则启动php脚本。
php脚本案例
cat run.php
<?php
do {
$message = number_format(microtime(true), 4, '.', '')
. ' '
. memory_get_usage()
. PHP_EOL;
file_put_contents('log.txt', $message, FILE_APPEND);
sleep(1);
} while (true);
&(job方式)
控制台执行run.php
[sy@sy-pc daemon]$ php run.php &
[1] 7876
查看是否执行,上文和下文得到的7868,是进程id。
[sy@sy-pc daemon]$ ps aux|grep run.php|grep -v grep
sy 7876 0.3 1.1 332044 20960 pts/0 S 23:11 0:00 php run.php
查看日志文件
[sy@sy-pc daemon]$ tail -f log.txt
1565021046.4876 677680
1565021047.4909 677680
杀死进程
kill `ps aux|grep run.php|grep -v grep|awk '{print $2}'`
shell脚本
为防止PHP脚本意外不工作(意外退出),写一个shell脚本,定时监控PHP脚本的执行情况,
shell监控脚本的编写,注意php二进制文件写绝对路径
。
vim /server/script/php_monitor.sh
#! /bin/bash
alive=`ps aux|grep run.php|grep -v grep|wc -l`
if [ ${alive} -eq 0 ];then
/application/php/bin/php /绝对路径/run.php > /dev/null 2>&1
fi
#date +%Y-%m-%d\ %H:%M:%S >> /wwwroot/sy.net/daemon/date.txt
为shell脚本添加执行权限
chmod +x /server/script/php_monitor.sh
添加计划任务(每分钟检测一次)
[root@sy-pc ~]# echo '* * * * * /server/script/php_monitor.sh > /dev/null 2>&1' >> /var/spool/cron/root
[root@sy-pc ~]# tail -1 /var/spool/cron/root
* * * * * /server/script/php_monitor.sh > /dev/null 2>&1
开启定时任务
CentOS 7
[root@sy-pc ~]# systemctl start crond
nohup
参考:https://blog.youkuaiyun.com/zhang197093/article/details/52226349
参考文献
[1] 如何将我的php脚本以守护进程的方式一直运行[DB|OL]. https://blog.youkuaiyun.com/qq_35396905/article/details/80856192 .
[2] php使用redis作为消息队列–守护进程模式执行[DB|OL]. https://blog.youkuaiyun.com/qq_16059847/article/details/83899146 .
[3] php两种实现守护进程的方式[DB|OL]. https://blog.youkuaiyun.com/zhang197093/article/details/52226349 .