php 查看文件锁定状态_如何检测PHP脚本是否已经在运行?

你可以用一个锁文件。PHP的

flock()

函数为Unix的

flock

如果您没有显式地释放它们,那么当持有它们的进程终止时,操作系统将自动为您释放这些锁,即使它异常终止。

您还可以遵循松散的Unix约定,将锁文件设为“PID文件”——也就是说,在获取文件的锁时,让脚本将其PID写入该文件。即使您从未在脚本中阅读过此内容,但如果您的脚本挂起或变得疯狂,并且您希望找到它的PID以便手动杀死它,则会很方便。

#!/usr/bin/php

$lock_file = fopen('path/to/yourlock.pid', 'c');

$got_lock = flock($lock_file, LOCK_EX | LOCK_NB, $wouldblock);

if ($lock_file === false || (!$got_lock && !$wouldblock)) {

throw new Exception(

"Unexpected error opening or locking lock file. Perhaps you " .

"don't have permission to write to the lock file or its " .

"containing directory?"

);

}

else if (!$got_lock && $wouldblock) {

exit("Another instance is already running; terminating.\n");

}

// Lock acquired; let's write our PID to the lock file for the convenience

// of humans who may wish to terminate the script.

ftruncate($lock_file, 0);

fwrite($lock_file, getmypid() . "\n");

/*

The main body of your script goes here.

*/

echo "Hello, world!";

// All done; we blank the PID file and explicitly release the lock

// (although this should be unnecessary) before terminating.

ftruncate($lock_file, 0);

flock($lock_file, LOCK_UN);

只要把你的锁文件的路径设置到你喜欢的任何地方。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值