Check if file is locked

In PHP, how can I check if a file has already been locked with flock ? For example, if another script run caused the following:

 $fp = fopen('thefile.txt', 'w'); flock($fp, LOCK_EX); 
+5
source share
2 answers
 if (!flock($fp, LOCK_EX|LOCK_NB, $wouldblock)) { if ($wouldblock) { // another process holds the lock } else { // couldn't lock for another reason, eg no such file } } else { // lock obtained } 

As described in the docs , use LOCK_NB to make a non-blocking attempt to obtain a lock, and if it fails, check $wouldblock to make sure something else holds the lock.

+17
source

Check it out as follows:

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

All Articles