PHP flock文件锁

http://hxsdit.com/1110

PHP自带了文件锁函数:
bool flock ( int $handle , int $operation [, int &$wouldblock ] )
$handle 是打开的文件指针;
$operation 可以是
“LOCK_SH”,共享锁定;“LOCK_EX”,独占锁定;“LOCK_UN”,释放锁定;“LOCK_NB”,防止flock锁定时堵塞。
这里主要说说“LOCK_EX”和“LOCK_NB”。
比如我们有两个文件,如下。
flocka.php

1 2 3 4 5 6 7 8 9 10     $file = 'temp.txt';
    $fp = fopen($file,'a');
 
    for($i = 0;$i < 5;$i++)
    {
        fwrite($fp, "11111111 ");
        sleep(1);
    }
 
    fclose($fp);


flockb.php

1 2 3 4 5 6 7 8 9     $file = 'temp.txt';
    $fp = fopen($file,'a');
 
    for($i = 0;$i < 5;$i++)
    {
        fwrite($fp, "22222222 ");
    }
 
    fclose($fp);

先运行flocka.php,然后马上运行flockb.php。
结果:
11111111
22222222
22222222
22222222
22222222
22222222
11111111
11111111
11111111
11111111
说明不加文件锁时,两个文件会同时对txt文件进行写入操作。
下面修改一下两个php文件的代码。
flocka.php

1 2 3 4 5 6 7 8 9 10 11 12 13     $file = 'temp.txt';
    $fp = fopen($file,'a');
 
    if(flock($fp,LOCK_EX))
    {
        for($i = 0;$i < 5;$i++)
        {
            fwrite($fp, "11111111 ");
            sleep(1);
        }
        flock($fp,LOCK_UN);
    }
    fclose($fp);

flockb.php

1 2 3 4 5 6 7 8 9 10 11 12 13     $file = 'temp.txt';
    $fp = fopen($file,'a');
 
    if(flock($fp,LOCK_EX))
    {
        for($i = 0;$i < 5;$i++)
        {
            fwrite($fp, "22222222 ");
        }
         flock($fp,LOCK_UN);
    }
 
    fclose($fp);

同样先运行flocka.php,然后马上运行flockb.php。
会发现在flocka.php运行结束前,flockb.php一直处于等待状态,只有当flocka.php运行结束后,flockb.php才会继续执行。
输出结果:
11111111
11111111
11111111
11111111
11111111
22222222
22222222
22222222
22222222
22222222
另外,在执行flock时,文件锁会自动释放。


<script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script>
阅读(980) | 评论(0) | 转发(2) |
给主人留下些什么吧!~~
评论热议
原文地址:https://www.cnblogs.com/ztguang/p/12648346.html