我有一个php进程用flock锁定一个文件。然后我启动另一个删除文件的进程。
在 Windows 上,我得到了无法删除锁定文件的正确行为,但是在 ubuntu(wsl 和完整的 Ubuntu 安装)上,我总是能够删除该文件。
我读过其他类似的问题,但他们似乎都测试错了。我很确定我正在正确地测试它。
更新:更彻底的测试。 阅读后为什么在打开的文件上取消链接成功?和文件系统中的删除队列我还需要测试读写。
测试方法。
- 打开终端并运行我的测试文件:
php test/flock_file_locking_with_splfileobject.php
锁定文件并等待 30 秒
- 打开第二个终端并运行以下命令:
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 上,我的第二个进程可以对文件执行任何它喜欢的操作,而第一个进程显然获得了成功的文件锁定。
显然,如果它只适用于 Windows,就不能相信羊群生产。有没有办法真正获得独占文件锁?
有任何想法吗?