所以我想锁定一个文件,这样我就可以看到php进程已经运行了。示例代码如下所示:
<?php
$file = fopen("test.txt","w+");
if (flock($file,LOCK_EX))
{
fwrite($file,"Write something");
sleep(10);
flock($file,LOCK_UN);
}
else
{
echo "Error locking file!";
}
fclose($file);
?>
但问题是,当我执行此文件并再次执行该文件时,第二个等待第一个完成锁定。所以两者都成功执行了。但只有第一个必须成功执行。知道如何做到这一点?
答案 0 :(得分:0)
听起来你不想让羊群阻塞?你只是希望第一个进程获得锁定而第二个进程失败?
为此,您可以使用LOCK_NB
标记停止阻止flock
来电:
$file = fopen("test.txt","r+");
if (flock($file,LOCK_EX | LOCK_NB))
{
fwrite($file,"Write something");
sleep(10);
flock($file,LOCK_UN);
}
else
{
echo "Error locking file!";
}
fclose($file);
PHP flock doc页面提供了更多信息 - http://php.net/manual/en/function.flock.php
答案 1 :(得分:0)
您可以使用第二个文件,例如&#34; test.txt.updated&#34;并保持那里的状态 - 即,是否&#34; test.txt&#34;已经更新或未更新。像下面这样的东西。请注意,我已打开&#34; text.txt&#34;在append-mode中查看两个并发运行是否真的只写了一次文件。
<?php
if (! ($f = fopen("text.txt", "a")) )
print("Cannot write text.txt\n");
elseif (! flock($f, LOCK_EX))
print("Error locking text.txt\n");
else {
print("Locked text.txt\n");
if (file_exists("text.txt.updated"))
print("text.txt already updated\n");
else {
print("Updating text.txt and creating text.txt.updated\n");
fwrite($f, "Write something\n");
if ($stamp = fopen("text.txt.updated", "w"))
fwrite($stamp, "whatever\n");
else
print("Oooooops, can't create the updated state file\n");
sleep(10);
}
flock($f, LOCK_UN);
}
?>