flock()
函数是否仅在代码执行的方法中使用时才有效?
例如,在以下代码中,锁定成功:
public function run()
{
$filePointerResource = fopen('/tmp/lock.txt', 'w');
if (flock($filePointerResource, LOCK_EX)) {
sleep(10);
} else {
exit('Could not get lock!');
}
}
但是,在以下代码中,锁定不成功:
public function run()
{
if ($this->lockFile()) {
sleep(10);
} else {
exit('Could not get lock!');
}
}
private function lockFile()
{
$filePointerResource = fopen('/tmp/lock.txt', 'w');
return flock($filePointerResource, LOCK_EX);
}
我还没有看到任何关于此的文档,所以我对这种行为感到困惑。我使用的是PHP版本5.5.35。
答案 0 :(得分:3)
我认为基于类的尝试存在的问题是,当lockFile
方法完成时,$filePointerResource
超出范围,这可能就是释放锁
这种方法支持那种理论
<?php
class test {
public function run()
{
$fp = fopen('lock.txt', 'w');
if ($this->lockFile($fp)) {
echo 'got a lock'.PHP_EOL;
sleep(5);
}
/*
* Not going to do anything as the attempt to lock EX will
* block until a lock can be gained
else {
exit('Could not get lock!'.PHP_EOL);
}
*/
}
private function lockFile($fp)
{
return flock($fp, LOCK_EX);
}
}
$t = new test();
$t->run();
因此,如果要通过多次调用类方法来锁定文件,最好将文件句柄保持为类属性,只要该类被实例化并且在范围内,它就会保留在范围内。
<?php
class test {
private $fp;
public function run()
{
$this->fp = fopen('lock.txt', 'w');
if ($this->lockFile()) {
echo 'got a lock'.PHP_EOL;
sleep(5);
}
/*
* Not going to do anything as the attempt to lock EX will
* block until a lock can be gained
else {
exit('Could not get lock!'.PHP_EOL);
}
*/
}
private function lockFile()
{
return flock($this->fp, LOCK_EX);
}
}
$t = new test();
$t->run();