Reputation: 28968
I found at the flock manual the following description:
By default, this function will block until the requested lock is acquired
Further below I found the following example code:
<?php
$fp = fopen("/tmp/lock.txt", "r+");
if (flock($fp, LOCK_EX)) { // acquire an exclusive lock
ftruncate($fp, 0); // truncate file
fwrite($fp, "Write something here\n");
fflush($fp); // flush output before releasing the lock
flock($fp, LOCK_UN); // release the lock
} else {
echo "Couldn't get the lock!";
}
fclose($fp);
?>
But is there any case where the script would actually return "Couldn't get the lock!"
? I thought it waits until the file lock.txt
gets unlocked. If the file never gets unlocked, then the script waits forever, right?
Further, I found this answer explaining the difference between exclusive and shared lock on unix: https://stackoverflow.com/a/11837714/2311074 Do these 4 rules also apply to flock in PHP (for example "If one or more shared locks already exist, exclusive locks cannot be obtained")?
Upvotes: 4
Views: 1651
Reputation: 140
On SunOS, if you opened the file in read mode, flock with LOCK_EX will always return false, even if the file is not locked. There is a comment to this effect on the PHP Manual flock page. The comment is down-voted to -2, but it is correct and bears repeating here:
flock on Solaris is slightly strange: it will fail if you try to get an exclusive lock on a file not opened for writing. That is, for reading files, you MUST use a shared lock. From the Solaris man page for flock: "Read permission is required on a file to obtain a shared lock, and write permission is required to obtain an exclusive lock." In contrast, this is from the Linux man page for flock: "The mode used to open the file doesn’t matter to flock." So, beware...
Many flock examples show the file being opened in read mode, but I can confirm the above comment. If you use flock with LOCK_EX, it will return return false on SunOS if you opened the file in read mode. Since Linux doesn't care which mode you use, it seems to me that one should always open the file in write mode when using flock with LOCK_EX.
Upvotes: 0
Reputation: 12233
Yes, blocking flock
can return false
.
It will happen if provided resource don't support locking
Samples are even provided in documentation
May only be used on file pointers returned by fopen() for local files, or file pointers pointing to userspace streams that implement the streamWrapper::stream_lock() method.
So if you try to lock ftp
or http
resource you will get false
, same will go for some wrappers e.g. zlib
or phar
.
flock() is not supported on antiquated filesystems like FAT and its derivates and will therefore always return FALSE under these environments.
Upvotes: 2
Reputation: 21531
Yes I found that when building flintstone it will not flock a compression streamed file...
$file = 'compress.zlib://path/to/file.txt';
$fp = fopen($file, 'w');
var_dump(flock($fp, LOCK_EX)); // false
Upvotes: 1