手机
当前位置:查字典教程网 >编程开发 >php教程 >强制PHP命令行脚本单进程运行的方法
强制PHP命令行脚本单进程运行的方法
摘要:复制代码代码如下:/***保证单进程**@paramstring$processName进程名*@paramstring$pidFile进程...

复制代码 代码如下:

/**

* 保证单进程

*

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

}

【强制PHP命令行脚本单进程运行的方法】相关文章:

PHP制作图型计数器的例子

PHP获取文件行数的方法

PHP实现多线程的两个方法

php删除文本文件中重复行的方法

开发大型PHP项目的方法

PHP基于MySQL数据库实现对象持久层的方法

PHP关联链接添加方法

php限制ip地址范围的方法

php简单实现快速排序的方法

PHP中4种常用的抓取网络数据方法

精品推荐
分类导航