TeAmEr
TeAmEr

Reputation: 4773

LOCK_NB Ignored

running this code twice :

$fp = @fopen('test.test', "wb");

    if (flock($fp, LOCK_NB | LOCK_EX)){
                @fwrite($fp, $data);
                echo 'written';
                sleep(5);
    }else{
        echo 'skipped , ok';
    }

    @flock($fp, LOCK_UN);
    @fclose($fp);

always gives me the output of "written"

Means the LOCK_NB is skipped , any clues (on both winbdows and unix)

EDIT (2012-03-29 still not fixed): https://bugs.php.net/bug.php?id=54453&edit=3 PHP Bug #54453

Upvotes: 7

Views: 2069

Answers (2)

TeAmEr
TeAmEr

Reputation: 4773

LOCK_NB works only when :

  1. File is locked with LOCK_SH and you do a LOCK_EX|LOCK_NB
  2. File is locked with LOCK_EX and you do a LOCK_SH|LOCK_NB

LOCK_NB is ignored if :

  1. File is locked with LOCK_EX and you do a LOCK_EX|LOCK_NB
  2. File is locked with LOCK_SH and you do a LOCK_SH|LOCK_NB

i guess this is a bug ? or they need to make a LOCK_NB2 ? i reported this as a bug to PHP.NET .

EDIT (2012-03-22 still not fixed): https://bugs.php.net/bug.php?id=54453&edit=3 PHP Bug #54453

Upvotes: 0

oxygen
oxygen

Reputation: 6039

When using Apache+PHP I was tricked into believing LOCK_NB was ignored (it wasn't, it was the browser waiting for the first request to finish).

Because I was making 2 requests with the same browser, the browser was waiting for the first call to finish before making the next one (even ignoring a "Connection: close" header).

Using 2 separate browsers (in my case Chrome + Firefox, or Chrome + wget on the server) I concluded LOCK_NB worked just fine.

If a file in w+ mode was locked with LOCK_EX | LOCK_NB, attempting another LOCK_EX | LOCK_NB on the same file returned false (the intended behaviour).

Upvotes: 21

Related Questions