• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

php 搞代码 3年前 (2022-01-25) 24次浏览 已收录 0个评论

复制代码 代码如下:
/**
* 保证单进程
*
* @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=”);

2本文来源gao!daima.com搞$代!码网

搞代gaodaima码

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”);
}


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:强制PHP命令行脚本单进程运行的方法_PHP
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址