您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

强制PHP命令行脚本单进程运行的方法_PHP

2024/4/28 6:26:45发布16次查看
复制代码 代码如下:
 /**
  * 保证单进程
  *
  * @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);
}
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product