Question

In PHP, how can I test if a file has already been locked with flock? For example, if another running script has called the following:

$fp = fopen('thefile.txt', 'w');
flock($fp, LOCK_EX);
Was it helpful?

Solution

if (!flock($fp, LOCK_EX|LOCK_NB, $wouldblock)) {
    if ($wouldblock) {
        // another process holds the lock
    }
    else {
        // couldn't lock for another reason, e.g. no such file
    }
}
else {
    // lock obtained
}

As described in the docs, use LOCK_NB to make a non-blocking attempt to obtain the lock, and on failure check the $wouldblock argument to see if something else holds the lock.

OTHER TIPS

if(stream_get_meta_data($fp)['blocked'])
  echo 'file is locked';
else 
  echo 'file is not locked';

Check it like this:

if (!flock($file, LOCK_EX)) {
    throw new Exception(sprintf('File %s is locked', $file));
}

fwrite($file, $write_contents);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top