文件()在读取时锁定文件吗? [英] Does file() lock the file when reading?

查看:196
本文介绍了文件()在读取时锁定文件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用file()来读取文件,如带有制表符的数组。我想锁定文件,但我似乎无法得到flock()在文件上工作。可以这样做吗?如果是这样,怎么样?如果没有,文件()是否从头开始锁定文件,并缓解任何潜在的共享问题? 解决方案

根据文档(特别是注释),它不会读取文件通过 flock 锁定。

您有两种选择。
$ b


  1. fgets 读取文件(不检查错误):

      $ f = fopen($ file,'r'); 
    flock($ f,LOCK_SH);
    $ data = array();
    while($ row = fgets($ f)){
    $ data [] = $ row;
    }
    flock($ f,LOCK_UN);
    fclose($ f);


  2. file c $>使用一个单独的lockfile:

    $ $ $ $ f $ f = fopen($ file。'.lock','w' );
    flock($ f,LOCK_SH);
    $ data = file($ file);
    flock($ f,LOCK_UN);
    fclose($ f);
    unlink($ file。'.lock');



I'm using file() to read through a file like an array with tabs. I want to lock the file but I cannot seem to get flock() working on the file. Is it possible to do this? If so, how? If not, does the file() lock the file from the start and alleviate any potential sharing problems?

解决方案

According to the documentation (specifically the comments), it won't read a file that was locked via flock.

You have 2 alternatives.

  1. Read the file with fgets (without checks for errors):

    $f = fopen($file, 'r');
    flock($f, LOCK_SH);
    $data = array();
    while ($row = fgets($f)) {
        $data[] = $row;
    }
    flock($f, LOCK_UN);
    fclose($f);
    

  2. Read the file with file() and using a separate "lockfile":

    $f = fopen($file . '.lock', 'w');
    flock($f, LOCK_SH);
    $data = file($file);
    flock($f, LOCK_UN);
    fclose($f);
    unlink($file . '.lock');
    

这篇关于文件()在读取时锁定文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆