如何写好php守护进程,php守护进程编程要点

发布时间:2020-02-29编辑:脚本学堂
php守护进程的实现代码,php守护进程的编程实例,在php中将程序代码处理为守护进程,php可以直接进行守护进程的启动与终止,一起学习下。

php守护进程实例,php可以直接进行守护进程的启动与终止的。

php也是可以直接进行守护进程的启动与终止的,相对于shell来说会简单很多,php的守护进程要实现自动重启还是要依赖于shell的crontab日程表,每隔一段时间去执行一次脚本看脚本是否需要重启,如果需要则杀掉进程删除RunFile文件,重新启动并在RunFile文件中写入pid。

例子:
 

复制代码 代码示例:
<?php  
function start($file){
$path = dirname(__FILE__).'/';
$runfile = $path.$file.'.run';
$diefile = $path.$file.'.die';
$file = $path."data/{$file}.php";
clearstatcache();
if(file_exists($runfile)){
$oldpid = file_get_contents($runfile);
$nowpid = shell_exec("ps aux | grep 'php -f process.php' | grep ${oldpid} | linuxjishu/13830.html target=_blank class=infotextkey>awk '{print $2}'");
//如果runfile中的pid号可以匹配到正在运行的,并且上次访问runfile的时间和现在相差小于5min则返回
if(($oldpid == $nowpid) && (time() - fileatime($runfile) < 300)){
echo "$file is circle runing no";
return;
}else{
//pid号不匹配或者已经有300秒没有运行循环语句,直接杀掉进程,重新启动
$pid = file_get_contents($runfile);
shell_exec("ps aux | grep 'php -f process.php' | grep {$pid} | xargs --if-no-run-empty kill");
}
}else{
//将文件pid写入run文件
if(!($newpid = getmypid()) || !file_put_contents($runfile,$newpid)){
return;
}
while(true){
//收到结束进程新号,结束进程,并删除相关文件
if(file_exists($diefile) && unlink($runfile) && unlink($diefile)){
return;
}
/*这里是守护进程要做的事*/
file_put_contents($file,"I'm Runing Now".PHP_EOL,FILE_APPEND);
/***********************/
touch($runfile);
sleep(5);
}
}
}
start("test");

php写守护进程注意几点:
1、函数clearstatcache()函数那里,查官方手册可以知道该函数是清除文件状态缓存的,当在一个脚本中多次检查同一个文件的缓存状态时如果不用该函数就会出错,受该函数影响的有:stat(), lstat(), file_exists(), is_writable(),is_readable(), is_executable(), is_file(), is_dir(), is_link(),filectime(), fileatime(), filemtime(), fileinode(), filegroup(),fileowner(), filesize(), filetype(), fileperms().
2、在多次运行该脚本时,会在运行前进行检测,上次执行循环的时间距离现在大于300s或者pid号不匹配都会重启该进程(时间在每次执行循环式都要更新touch)。
3、自动重启也用到了crontab的日程表,将该文件添加入日程表:
 

crontab -e
#打开日程表,inset模式
*/3 * * * * /usr/bin/php -f process.php
#每3分钟执行一次,放置进程挂掉

二、用php守护另一个php进程的例子

用php守护另一个php进程的例子

要用php守护另一个php进程(apache模块的运行的,还有nginx等运行的除外)

a.php要守护b.php
在b.php中 通过 getmypid()函数获取当前进程的id,并将id写入c.pid文件中,如果程序执行完成将c.pid文件删除或清空
在a.php中 验证c.pid是否存在 ,是否为空,如果不为空,将pid读出,通过exec执行 ps -p pid|grep 文件名来判断是否运行,判断后执行相应操作
可能有人要问,为什么不直接 ps aux|grep 文件名,这里主要是考虑到文件重名的情况下会出问题

a.php 代码
 

复制代码 代码示例:
<?
$id=intval($argv[1]);
if(!file_exists(‘pid'.$id.'.pid')){
echo “not run”;
exit;
}
$content=file_get_contents(‘pid'.$id.'.pid');
if(empty($content)){
echo “not run”;
exit;
}
exec(“ps p “.$content.'|grep b.php',$pids);
if(count($pids)>0) echo(‘runing');
else{echo ‘not run';}
?>

b.php代码
 

复制代码 代码示例:
<?
$id=intval($argv[1]);
if(empty($id))exit;
file_put_contents(‘pid'.$id.'.pid',getmypid());
while(1){
file_put_contents(‘pid'.$id.'.pid',getmypid());
sleep(100);
}
?>