时时商务社区

标题: 强制PHP命令行脚本单进程运行的方法 [打印本页]

作者: qz234    时间: 2018-2-14 05:59

            [U]复制代码[/U] 代码如下:
/**
  * 保证单进程
  *
  * @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;
}
使用方法:
[U]复制代码[/U] 代码如下:
if (singleProcess(getCurrentCommand(), 'path/to/script.pid'))
{
    // code goes here
}
else
{
exit("Sorry, this script file has already been running ...\n");
}
            
            
您可能感兴趣的文章:
  • 随机广告显示(PHP函数)
  • 用PHP实现小型站点广告管理(修正版)
  • 用PHP实现小型站点广告管理
  • 用PHP实现的随机广告显示代码
  • PHP运行时强制显示出错信息的代码
  • php 随机排序广告的实现代码
  • php 广告调用类代码(支持Flash调用)
  • 适用于抽奖程序、随机广告的PHP概率算法实例
  • php广告加载类用法实例
  • php强制运行广告的方法
            




    欢迎光临 时时商务社区 (http://bbs.4435.cn/) Powered by Discuz! X3.2