为什么这个函数返回 false?

Why is this function returning false?

我有以下代码:

function lock() {
    if($lock = @fopen('lock.txt', 'x')) {
        fwrite($lock, getmypid());
        fclose($lock);
        return true;
    }
    else {
        return false;
    }
}

$response = lock();

当我运行代码时,会创建文件 lock.txt 并将 PID 放入文件中。但是,函数returns false。这到底是怎么回事?

fopen(lock.txt): failed to open stream: File exists in /xxx on line 22.

问题是,我确定该文件不存在——我什至在运行代码之前返回并删除了它。该代码创建了文件,但仍然 returns false。

我检查以确保没有其他代码正在创建该文件。我什至等了 30 秒,看看文件是否重新出现 -- 它不会自己出现,它只会在我执行此代码后出现。

fopen()模式Xhttp://php.net/manual/en/function.fopen.php

Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING.

如果文件已经存在,fopen() 调用将失败,返回 FALSE 并生成 E_WARNING.

级别的错误

如果您不使用 @ 错误抑制,您将看到警告。

您可能需要模式 W

Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

PHP Manual 声明模式 x:

Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.

该函数返回 false,因为 @fopen('lock.txt', 'x') returns false(该文件已经存在),这导致 $lock = @fopen('lock.txt', 'x') 评估为 false,触发分支到 return false;.