当前位置:首页 > PHP教程 > php高级应用 > 列表

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

发布:smiling 来源: PHP粉丝网  添加日期:2020-11-15 19:57:50 浏览: 评论:0 

本文介绍了一个强制PHP在单进程中执行的函数,多用在php命令行中和一些特殊需求的地方,需要的朋友可以参考下,代码如下:

  1. /** 
  2.  * 保证单进程 
  3.  * 
  4.  * @param string $processName 进程名 
  5.  * @param string $pidFile 进程文件路径 
  6.  * @return boolean 是否继续执行当前进程 
  7.  */ 
  8. function singleProcess($processName, $pidFile) 
  9. { 
  10.  if (file_exists($pidFile) && $fp = @fopen($pidFile,"rb")) 
  11.  { 
  12.   flock($fp, LOCK_SH); 
  13.   $last_pid = fread($fp, filesize($pidFile)); 
  14.   fclose($fp); 
  15.  
  16.   if (!emptyempty($last_pid)) 
  17.   { 
  18.    $command = exec("/bin/ps -p $last_pid -o command="); 
  19.  
  20.    if ($command == $processName) 
  21.    { 
  22.     return false; 
  23.    } 
  24.   } 
  25.  } 
  26.  
  27.  $cur_pid = posix_getpid(); 
  28.  
  29.  if ($fp = @fopen($pidFile, "wb")) 
  30.  { 
  31.   fputs($fp, $cur_pid); 
  32.   ftruncate($fp, strlen($cur_pid)); 
  33.   fclose($fp); 
  34.  
  35.   return true; 
  36.  } 
  37.  else 
  38.  { 
  39.   return false; 
  40.  } 
  41. } 
  42.  
  43. /** 
  44.  * 获取当前进程对应的Command 
  45.  * 
  46.  * @return string 命令及其参数 
  47.  */ 
  48. function getCurrentCommand() 
  49. { 
  50.  $pid     = posix_getpid(); 
  51.  $command = exec("/bin/ps -p $pid -o command="); 
  52.  
  53.  return $command; 
  54. } 

使用方法:

  1. if (singleProcess(getCurrentCommand(), 'path/to/script.pid')) 
  2. { 
  3.     // code goes here 
  4. } 
  5. else 
  6. { 
  7.  exit("Sorry, this script file has already been running ...\n"); 
  8. } 

Tags: PHP命令行 PHP单进程

分享到: