PHPコマンドラインスクリプト単一プロセスの実行を強制する方法

1540 ワード

 
  
 /**
  *
  *
  * @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 ...
");
}