当前位置: 首页 > 工具软件 > (R)?ex > 使用案例 >

flock lock ex php,php – flock有可能用LOCK_EX返回false吗?

凌长恨
2023-12-01

标签:php

By default, this function will block until the requested lock is

acquired

在下面我发现了以下示例代码:

$fp = fopen("/tmp/lock.txt", "r+");

if (flock($fp, LOCK_EX)) { // acquire an exclusive lock

ftruncate($fp, 0); // truncate file

fwrite($fp, "Write something here\n");

fflush($fp); // flush output before releasing the lock

flock($fp, LOCK_UN); // release the lock

} else {

echo "Couldn't get the lock!";

}

fclose($fp);

?>

但有没有任何情况下脚本实际上会返回“无法锁定!”?我以为它一直等到文件lock.txt解锁.如果文件永远不会被解锁,那么脚本会永远等待,对吧?

此外,我发现这个答案解释了unix上的独占锁和共享锁之间的区别:https://stackoverflow.com/a/11837714/2311074

这四个规则是否也适用于PHP中的flock(例如“如果已经存在一个或多个共享锁,则无法获得独占锁”)?

解决方法:

是的,阻止flock可以返回false.

如果提供的资源不支持锁定,则会发生这种情况

样本甚至在文档中提供

May only be used on file pointers returned by fopen() for local files,

or file pointers pointing to userspace streams that implement the

streamWrapper::stream_lock() method.

因此,如果您尝试锁定ftp或http资源,您将得到错误,同样会用于某些包装器,例如zlib或phar.

flock() is not supported on antiquated filesystems like FAT and its

derivates and will therefore always return FALSE under these

environments.

标签:php

来源: https://codeday.me/bug/20190627/1308714.html

 类似资料: