用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);

  }

  ?>