Home > Backend Development > PHP Tutorial > file - php file locking

file - php file locking

WBOY
Release: 2016-08-04 09:22:13
Original
1237 people have browsed it

file - php file locking
file - php file locking
As shown in the picture, when I run two scripts at the same time, why can the second script write to the file immediately? Isn’t the file locked in the first script?

Reply content:

file - php file locking
file - php file locking
As shown in the picture, when I run two scripts at the same time, why can the second script write to the file immediately? Isn’t the file locked in the first script?

PHP reading and writing files are locked. For details, please refer to this http://www.jb51.net/article/81246.htm

Your second fwrite is operated without applying for the exclusive lock LOCK_EX before, and of course it will be written.
You must apply for LOCK_EX before both fwrites, so that it can have a locking effect.

<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>
Copy after login
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template