note 58848 rejected from function.flock by nlopess

From: Date: Thu, 17 Nov 2005 18:34:59 +0000
Subject: note 58848 rejected from function.flock by nlopess
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-98718@lists.php.net to get a copy of this message
Note Submitter: phpcoder at cyberpimp dot pimpdomain dot com ---- Maybe I'm missing something here, but would the following not work reliably? <?php $sharedfile = 'somefile.dat'; $lockedfile = 'somefile.da_'; $timeout = false; ignore_user_abort(true); # prevent premature termination permanently "locking" the file while (false === (rename($sharedfile, $lockedfile))) { # "lock" the file //Optional: Add code here for retry timeout. Be sure to then set $timeout = true } if (!$timeout) { //Add code here to open $lockedfile and write data rename($lockedfile, $sharedfile); # "unlock" the file }else{ //Optional: error message for timeout } ignore_user_abort(false); # return script termination back to normal ?> The rename() function is used to "lock" the file. If the filename doesn't exist (because another process has the file "locked", ie. renamed to something else), rename() returns false. Only when rename() returns true will the script continue to write to the (renamed) file. This can only happen when the script has successfully "locked" the file. By surrounding everything between the ignore_user_timeout() statements, closed connections wont prematurely terminate the script and leave the file permanently "locked". Even if there is still a risk of killed scripts leaving the file permanently "locked" (that is, renamed to $lockedfile), code can be added in the while() loop to check the date/time of $lockedfile and ignore the existing "lock" by breaking out of the loop with $timeout = false if the date/time is considered too old.

« previous php.notes (#98718) next »