Windows 和 Linux 上的 PHP flock() 行为差异 [英] PHP flock() behaviour difference on Windows vs Linux

查看:24
本文介绍了Windows 和 Linux 上的 PHP flock() 行为差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Windows 机器和 Linux 机器上执行相同的代码片段.两者都运行 PHP 5.4:

I am executing the same code snippet on a Windows machine and a Linux machine. Both are running PHP 5.4:

$file = "lock.txt";
$fp = fopen($file, "w+");
flock($fp, LOCK_EX);
var_dump(@file_put_contents($file, 'hello' . rand()));
flock($fp, LOCK_UN);
fclose($fp);

在 Windows 机器上,file_put_contents() 操作失败并返回 false.在 Linux 机器上,它成功了.

On the Windows machine, the file_put_contents() operation fails and returns false. On the Linux machine, it succeeds.

我试图弄清楚这两种行为中的哪一种实际上是正确的,以及我如何在两个系统中标准化行为(为了记录,我的目标是让 file_put_contents() 失败. 我不需要它是健壮的或原子的,我只是想让它失败.)

I'm trying to figure out which of these two behaviours is actually correct and how I can standardize the behaviour across both systems (for the record, my goal is to have the file_put_contents() fail. I don't need it to be robust or atomic, I just want it to fail.)

我已经看到很多关于这个主题的其他问题,但它们似乎都与访问同一个文件的多个脚本有关,这里不是这种情况.

I have seen plenty of other questions about this topic, but they all seem to relate to multiple scripts accessing the same file, which isn't the situation here.

推荐答案

flock() 的文档似乎确实回答了这个问题,尽管不够全面.文档确实声明

It appears the documentation for flock() does answer this question, albeit not as fully as it could. The documentation does state

flock() 在 Windows 上使用强制锁定而不是建议锁定

flock() uses mandatory locking instead of advisory locking on Windows

这已经足够清楚了,但我被第一条评论拒之门外 读取

which is clear enough but I was thrown off by the first comment which reads

Flock 仅使用 ADVISORY 锁定;也就是说,其他进程可能完全忽略锁

Flock utilizes ADVISORY locking only; that is, other processes may ignore the lock completely

我将其解释为我自己的进程会隐式地尊重锁;实际上它的意思似乎是这样的,我们假设——一旦你首先使用 flock()——你会记得在任何写入之前检查锁的状态,但请记住其他程序可能不会这样做."

I was interpreting that to mean that my own process would respect the lock implicitly; actually it seems to mean something like, "We assume that--once you're using flock() in the first place--you will remember to check the lock's status before any writes, but remember that other programs may not be doing so."

这篇关于Windows 和 Linux 上的 PHP flock() 行为差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆