Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php flock behaviour when file is locked by one process

Tags:

php

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)
{
    foreach($data as $line)
        if(trim($line) != $DELETE_LINE)
            $out[] = $line;
}
$fp = fopen("foo.txt", "w+");
flock($fp, LOCK_EX);
foreach($out as $line)
    fwrite($fp, $line);
flock($fp, LOCK_UN);
fclose($fp); 

I want to know if some user is currently executing this script and file "foo.txt" is locked, in same time or before completion of its execution, if some other user calls this script, then what will happen? Will second users process wait for unlocking of file by first users? or line deletion by second users input will fail?

like image 940
Dr. DS Avatar asked Sep 16 '13 16:09

Dr. DS


1 Answers

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
}
like image 130
Barmar Avatar answered Oct 24 '22 07:10

Barmar