PHP 群在 ubuntu 中没有任何影响

问题描述

我有一个 PHP 进程用 flock 锁定一个文件。 然后我开始另一个删除文件的进程。

在 Windows 上,我得到了无法删除锁定文件的正确行为,但是在 ubuntu(wsl 和完整的 Ubuntu 安装)上,我总是能够删除文件

我已经阅读了其他类似的问题,但它们似乎都测试错误。 我很确定我正在正确地测试这个。

更新:更彻底的测试。 阅读Why is unlink successful on an open file?文件系统中的删除队列后,我还需要测试读写。

测试方法

  1. 打开终端并运行我的测试文件

PHP test/flock_file_locking_with_splfileobject.PHP ? 锁定文件并等待 30 秒

  1. 打开第二个终端并运行以下命令:
PHP test/flock_file_locking_with_splfileobject.PHP read
PHP test/flock_file_locking_with_splfileobject.PHP write
PHP test/flock_file_locking_with_splfileobject.PHP delete

这是test/flock_file_locking_with_splfileobject.PHP内容

查看描述我得到的输出代码中的注释。

<?PHP
$me = array_shift($argv);

$command = array_shift($argv);

$fileName = 'cats';

switch ($command) {
    case 'delete':
        //attempt to delete the file
        if (!unlink($fileName)) {
            echo "Failed to delete file!";
            exit(1);
        }
        echo "File was deleted:";
        var_dump(file_exists($fileName) === false);
        //on linux I get File was deleted:bool(true)
        //on windows I get 'PHP Warning:  unlink(cats): Resource temporarily unavailable'
        break;
    case 'write':
        $written = file_put_contents($fileName,'some datah!');
        echo "Written bytes:";
        var_dump($written);
        //on Linux I get 'Read: string(21) "file should be locked"'
        // OR 'Read: string(11) "some datah!"' if I run the write command first.
        //on windows i get Warning: file_put_contents(): Only 0 of 11 bytes written,possibly out of free disk space
        break;
    case 'read':
        $read = file_get_contents($fileName);
        echo "Read: ";
        var_dump($read);
        // on Linux i get 'Written bytes:int(11)'
        // on windows I get no error but I get no data 'Read: string(0) ""'
        break;
    default:
        $file = new \SplFileObject($fileName,'a+');//file gets created by a+
        if (! $file->flock(LOCK_EX)) {
            echo "Unable to lock the file.\n";
            exit(1);
        }
        $file->fwrite('file should be locked');
        echo "File should Now be locked,try running the delete/write/read commands in another terminal.","I'll wait 30 seconds and try to write to the file...\n";
        sleep(30);
        if (! $file->fwrite('file is Now unlocked')) {
            echo "Unable to write to file.\n";
            exit(1);
        }
        //in either system this file write succeeds regardless of whats going on.
        break;
}
echo "\n";

Windows 运行正常,但在 Linux 上, 我的第二个进程可以对文件做任何它喜欢的事情,而第一个进程显然获得了成功的文件锁定。

显然,如果 flock 仅适用于 Windows,就不能信任它。 有没有办法真正获得独占文件锁?

有什么想法吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...