WindBridges
WindBridges

Reputation: 753

What is the reason for flock() to return FALSE?

PHP manual says that calling flock returns TRUE if lock was successful and FALSE if not. If file is blocked by other process, then flock should wait until it's unblocked (since we don't use LOCK_NB). There is nothing about the timeout in docs, which can interrupt waiting, so obviously flock will wait infinitely until gets lock.

But sometime I getting FALSE from flock() in my multithreaded scripts. What is the reason for that?

Upvotes: 4

Views: 1140

Answers (2)

Philipp
Philipp

Reputation: 11341

Another reason for this can be a "security" restriction in php.ini.

So also check with phpinfo() whether flock is listed in the disabled_functions list:

Example of phpinfo() with disabled flock function

Upvotes: 0

Michał Maluga
Michał Maluga

Reputation: 473

I've had similar problem recently and made a small research. If you look at the source code of the PHP flock function, you can see the implementation depends on OS the code is compiled on.

For *nix systems there is:

ret = fcntl(fd, operation & LOCK_NB ? F_SETLK : F_SETLKW, &flck);

It means OS level fcntl function is used.

Manual for fcntl says:

F_SETLKW (struct flock *)

As for F_SETLK, but if a conflicting lock is held on the file, then wait for that lock to be released. If a signal is caught while waiting, then the call is interrupted and (after the signal handler has returned) returns immediately (with return value -1 and errno set to EINTR; see signal(7)).

Upvotes: 2

Related Questions