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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
hswner
Forum Newbie
Posts: 3
Joined: Mon Mar 17, 2008 12:47 pm

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

Post 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
hswner
Forum Newbie
Posts: 3
Joined: Mon Mar 17, 2008 12:47 pm

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

Post 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);
    }
?>
Post Reply