无为清净楼资源网 Design By www.qnjia.com

复制代码 代码如下:
 /**
  * 保证单进程
  *
  * @param string $processName 进程名
  * @param string $pidFile 进程文件路径
  * @return boolean 是否继续执行当前进程
  */
 function singleProcess($processName, $pidFile)
 {
  if (file_exists($pidFile) && $fp = @fopen($pidFile,"rb"))
  {
   flock($fp, LOCK_SH);
   $last_pid = fread($fp, filesize($pidFile));
   fclose($fp);

   if (!empty($last_pid))
   {
    $command = exec("/bin/ps -p $last_pid -o command=");

    if ($command == $processName)
    {
     return false;
    }
   }
  }

  $cur_pid = posix_getpid();

  if ($fp = @fopen($pidFile, "wb"))
  {
   fputs($fp, $cur_pid);
   ftruncate($fp, strlen($cur_pid));
   fclose($fp);

   return true;
  }
  else
  {
   return false;
  }
 }

 /**
  * 获取当前进程对应的Command
  *
  * @return string 命令及其参数
  */
 function getCurrentCommand()
 {
  $pid     = posix_getpid();
  $command = exec("/bin/ps -p $pid -o command=");

  return $command;
 }

使用方法:
复制代码 代码如下:
if (singleProcess(getCurrentCommand(), 'path/to/script.pid'))
{
    // code goes here
}
else
{
 exit("Sorry, this script file has already been running ...\n");
}

标签:
PHP,单进程,强制单进程

无为清净楼资源网 Design By www.qnjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
无为清净楼资源网 Design By www.qnjia.com