Heim  >  Artikel  >  Backend-Entwicklung  >  file - php 文件加锁

file - php 文件加锁

WBOY
WBOYOriginal
2016-08-04 09:22:131173Durchsuche

file - php 文件加锁
file - php 文件加锁
如图,我同时运行两个脚本时,为什么第二个脚本可以立即写入文件呢,文件不是在第一个脚本中被加锁了吗

回复内容:

file - php 文件加锁
file - php 文件加锁
如图,我同时运行两个脚本时,为什么第二个脚本可以立即写入文件呢,文件不是在第一个脚本中被加锁了吗

PHP读写文件是有锁的 具体可以参考这个http://www.jb51.net/article/81246.htm

你的第二个fwrite之前没有申请排它锁LOCK_EX就操作了,当然会被写入.
你必须两个fwrite之前都应该申请LOCK_EX,这样才能起到加锁的作用.

<code>foo1.php:
<?php header('Content-Type: text/plain; charset=utf-8');
if(file_exists('arr.php')) {
    $arr = require 'arr.php'; //先require后fopen
} else {
    file_put_contents('arr.php','<?php return array();');
}
$fp = fopen('arr.php', 'r+'); //读写方式打开,将文件指针指向文件头
if(flock($fp,LOCK_EX)) { //阻塞到获取排它锁
    $arr['name'] = __FILE__;
    ftruncate($fp, 0); //截断文件
    fwrite($fp,'<?php return '.var_export($arr, true).';');
    var_export($arr);
    fflush($fp); //在释放锁之前刷新输出
    sleep(10); //睡眠10秒,在此期间访问foo2.php将被阻塞
    flock($fp, LOCK_UN); //释放锁定
}
fclose($fp);

foo2.php:
<?php
header('Content-Type: text/plain; charset=utf-8');
$arr = require 'arr.php';
$fp = fopen('arr.php', 'r+');
if(flock($fp,LOCK_EX)) {
    $arr['name'] = __FILE__;
    ftruncate($fp, 0);
    fwrite($fp,'<?php return '.var_export($arr, true).';');
    var_export($arr);
    fflush($fp);
    flock($fp, LOCK_UN);
}
fclose($fp);</code></code>
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn