gpt4 book ai didi

php - flock 有可能用 LOCK_EX 返回 false 吗?

转载 作者:可可西里 更新时间:2023-10-31 23:16:26 25 4
gpt4 key购买 nike

我在 flock manual 找到了以下描述:

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

在下面我找到了以下示例代码:

<?php

$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);

?>

但是在任何情况下脚本实际上会返回 “Couldn't get the lock!”?我认为它会等到文件 lock.txt 解锁。如果文件永远不会解锁,那么脚本将永远等待,对吗?

此外,我发现这个答案解释了 unix 上排他锁和共享锁之间的区别:https://stackoverflow.com/a/11837714/2311074这 4 条规则是否也适用于 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.

因此,如果您尝试锁定 ftphttp 资源,您将得到 false,对于某些包装器,例如zlibphar

flock() is not supported on antiquated filesystems like FAT and its derivates and will therefore always return FALSE under these environments.

关于php - flock 有可能用 LOCK_EX 返回 false 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41443326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com