登录

php - 关于函数flock()的锁定问题!!!

a.php

$file3=fopen('a.txt','r+');
if(flock($file3,LOCK_EX+LOCK_NB)) {
    fwrite($file3,$_GET['s']) ;
    sleep(5);
    flock($file3,LOCK_UN);

} else{
    echo "文件锁定,不可写入内容!";
}

b.php

$file2=fopen('a.txt','r+');
fwrite($file2,$_GET['s']) ;
echo fread($file2,filesize('a.txt'));
fclose($file2);

先执行a.php时利用5秒间隔执行b.php
按理说由于a.php已经锁定,所以b.php,
无法写入,老师的视屏也是如此进行的
但是,我却不能和老师的一样运行,
结果依然是b.php写入的内容,a.php,并没有
锁定成功。

在下发现一个问题:就是我不能像视频里的老师一样利用间隔执行另一个脚本;
实际情况是:执行a.php完全结束后,才会在执行b.php。(前提是先刷新a.php,再刷新b.php)

我不清楚为什么会这样,请大家指教!

# PHP
迷茫迷茫2154 天前676 次浏览

全部回复(1) 我要回复

  • 天蓬老师

    天蓬老师2017-04-10 16:38:45

    PHP supports a portable way of locking complete files in an advisory
    way (which means all accessing programs have to use the same way of
    locking or it will not work). By default, this function will block
    until the requested lock is acquired; this may be controlled with the
    LOCK_NB option documented below.

    advisory lock - 你需要在 a.php 和 b.php 都调用flock()

    回复
    0
  • 取消回复发送