Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does LOCK_NB mean in flock?

Tags:

linux

php

What does LOCK_NB mean in the PHP flock command?

like image 720
Rami Dabain Avatar asked Mar 31 '11 22:03

Rami Dabain


Video Answer


1 Answers

LOCK_NB means non-blocking.

Usually when you try to lock a file, your PHP script execution will stop. The call to flock() then blocks it from resuming. It does so until a concurrent lock on the accessed file is removed.

Mostly your process is the only one trying to lock the file, so the blocking call to flock actually returns instantly. It's only if two processes lock the very same file, that one of them will be paused.

The LOCK_NB flag however will make flock() return immediately in any case. In that setting you have to check the returned status to see if you actually aquired the lock. As example:

while ( ! flock($f, LOCK_NB) ) {
    sleep(1);
}

Would more or less emulate the behaviour of the normal blocking call. The purpose of course is to do something else / meaningful (not just wait) while the file is still locked by another process.

like image 125
mario Avatar answered Sep 22 '22 14:09

mario