Home >Backend Development >PHP Tutorial >How to force a PHP command line script to run in a single process_PHP Tutorial

How to force a PHP command line script to run in a single process_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 10:32:44913browse

复制代码 代码如下:

 /**
* Guaranteed single process
*
* @param string $processName Process name
* @param string $pidFile Process file path
* @return boolean Whether to continue executing the current process
*/
 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;
  }
 }

 /**
* Get the Command
corresponding to the current process *
* @return string command and its parameters
*/
 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");
}

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/754797.htmlTechArticle复制代码 代码如下: /** * 保证单进程 * * @param string $processName 进程名 * @param string $pidFile 进程文件路径 * @return boolean 是否继续执行当前进程...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn