My server uses NFS (Network File System), and I'm unable to use PHP's flock() -function. Is there a way to lock files on an NFS or is there a need to do so?


Solution 1:

The manual page flock(2) had been out of date for a long time, but has since been updated to say (emphasis mine):

Since Linux 2.6.12, NFS clients support flock() locks by emulating them as byte-range locks on the entire file. This means that fcntl(2) and flock() locks do interact with one another over NFS. Since Linux 2.6.37, the kernel supports a compatibility mode that allows flock() locks (and also fcntl(2) byte region locks) to be treated as local; see the discussion of the local_lock option in nfs(5).

That is from the official man-pages web site, http://man7.org/linux/man-pages/man2/flock.2.html which shows the new version from man-pages 4.00

Linux 2.6.12 was released in 2005.

This was originally meant to be a comment on janneb's answer, but I didn't have the reputation at the time. The doc update happened in 2014: http://git.kernel.org/cgit/docs/man-pages/man-pages.git/commit/man2/flock.2?id=e449654fdb3f19aafc569df47d12bffdf6276236

Solution 2:

I don't know how the PHP flock() function is implemented, but assuming it's an interface to the flock() syscall, then it does not work at all over NFS. From the flock() manpage:

flock(2) does not lock files over NFS. Use fcntl(2) instead: that does work over NFS, given a sufficiently recent version of Linux and a server which supports locking.

And, of course, everything what a man page says, no matter how outdated, is the ultimate truth.

Solution 3:

flock() works just fine on Linux NFS, including from PHP. We use it extensively and have tested it thoroughly to verify it's working as desired. Check to see if you're running all of the necessary services on both the client and server. Look for "portmapper" and "rpc.statd". If they're not running, you need to figure out which init script starts them on your distro. On Debian-based distros it's "/etc/init.d/portmap" and "/etc/init.d/nfs-common".

From the client, run "rpcinfo -u $NFSSERVER status" and see if you get a response. On my setup, I get "program 100024 version 1 ready and waiting" as the result.

Oh, also bear in mind that in some circumstances NFS and statd can get upset if both the client and the server don't have reliable hostname entries for each other. Double check /etc/hosts on both machines.

Solution 4:

Just wanted to answer to myself. The solution can be found here: http://us3.php.net/manual/en/function.flock.php#82521