Page 1 of 1

File Locking in PHP: Do a LOCK_EX request "suspend" until ok

Posted: Mon Mar 17, 2008 12:51 pm
by hswner
Look at the example below

flock($fp, LOCK_EX); // do an exclusive lock
fwrite($fp, "Write something here\n");
flock($fp, LOCK_UN);

What happens if an exclusive lock on the file is already being hold by another user? Does this script suspend until the other user leaves the lock?
If not, what should I do in order to wait until it's allowed to write to the file?

OS: Windows, Unix

Re: File Locking in PHP: Do a LOCK_EX request "suspend" until ok

Posted: Tue Mar 18, 2008 4:37 pm
by hswner
the answer comes from the inquirer himself;

yes it does. to test it out run the script below twice simultaneously.

Code: Select all

<?php
    $fp = fopen("ftest.txt", "w");
    if (flock($fp, LOCK_EX)) {
        echo "Got it!\n";
        sleep(8);
        flock($fp, LOCK_UN);
    }
?>