Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
771 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...