Does file() lock the file when reading?

◇◆丶佛笑我妖孽 提交于 2019-12-10 19:11:07

问题


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?


回答1:


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');
    


来源:https://stackoverflow.com/questions/4789288/does-file-lock-the-file-when-reading

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!