Home  >  Article  >  Backend Development  >  关于函数flock()的锁定问题!!!

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

WBOY
WBOYOriginal
2016-06-06 20:20:581398browse

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)

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

回复内容:

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 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()

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn