php flock behaviour when file is locked by one process

前端 未结 1 1526
长情又很酷
长情又很酷 2020-12-14 12:10

Let\'s consider a sample php script which deletes a line by user input:

$DELETE_LINE = $_GET[\'line\'];
$out = array();
$data = @file(\"foo.txt\");
if($data)         


        
相关标签:
1条回答
  • 2020-12-14 12:40

    If you try to acquire an exclusive lock while another process has the file locked, your attempt will wait until the file is unlocked. This is the whole point of locking.

    See the Linux documentation of flock(), which describes how it works in general across operating systems. PHP uses fcntl() under the hood so NFS shares are generally supported.

    There's no timeout. If you want to implement a timeout yourself, you can do something like this:

    $count = 0;
    $timeout_secs = 10; //number of seconds of timeout
    $got_lock = true;
    while (!flock($fp, LOCK_EX | LOCK_NB, $wouldblock)) {
        if ($wouldblock && $count++ < $timeout_secs) {
            sleep(1);
        } else {
            $got_lock = false;
            break;
        }
    }
    if ($got_lock) {
        // Do stuff with file
    }
    
    0 讨论(0)
提交回复
热议问题