php - fopen(file,w+) 在我检查文件是否被 flock() 锁定之前截断文件

标签 php fopen flock

我有一个接收文件名和 json 对象以写入文本文件的函数。

对象已更新,需要完全替换文件的当前内容。每个站点访问者都有自己的文件。多次快速更改会导致文件被 fopen(file,w+) 截断,然后由于锁定而无法写入。最终结果是空文件。

我确信有一种标准的简单方法可以做到这一点,因为这是一项非常常见的事件。理想情况下,我正在寻找一种在 w+ 模式下使用 fopen 截断文件之前检查文件是否有锁的方法,或者一种切换模式的方法。

这似乎很奇怪,您必须使用 fopen() 截断文件以获取文件句柄以传递给 flock() 以检查它是否已锁定 --但你只是截断了它,那有什么意义呢?

这是我目前拥有的功能:

function updateFile($filename, $jsonFileData) {
    $fp = fopen($filename,"w+");
    if (flock($fp, LOCK_EX)) {  
        fwrite($fp, $jsonFileData);
        flock($fp, LOCK_UN);
        fclose($fp);
        return true;
    } else {
        fclose($fp);
        return false;
    }
}

最佳答案

示例 #1 来自 PHP manual将做你想做的稍作修改。使用 "c" mode打开文件进行写入,如果它不存在则创建它,并且不要截断它。

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

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

"c" mode 的完整描述:

Open the file for writing. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). The file pointer is positioned on the beginning of the file. This may be useful if it's desired to get an advisory lock (see flock()) before attempting to modify the file, as using 'w' could truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be used after the lock is requested).

看起来你不需要它,但如果你想同时读写,也有相应的"c+"模式。

关于php - fopen(file,w+) 在我检查文件是否被 flock() 锁定之前截断文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13039065/

相关文章:

c - 当其他文件正在尝试访问时,从文本文件中删除行

linux - 出现错误时释放 flock?

c - 如何在没有fopen的情况下读取C中的文本文件

php - 有没有一种可移植的方法可以在 flock() 上设置超时?

c - 在 Linux 中以独占方式打开一个设备文件

php - 如果文件存在php

php - 我的 magento 页面和单一产品内容仅在前端丢失,所有内容均已启用。如何刷新 session 数据以找到它?

PHP 强制下载导致 0 字节文件

php - FOSRestBundle 添加 http 基本认证

c - 是否可以防止添加 BOM 以输出 UTF-8 文件? ( Visual Studio 2005)