note 58848 added to function.flock
| From: | phpcoder at cyberpimp dot pimpdomain dot com | Date: | Thu, 17 Nov 2005 18:30:21 +0000 |
| Subject: | note 58848 added to function.flock | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-98717@lists.php.net to get a copy of this message | ||
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.
----
Manual Page -- http://www.php.net/manual/en/function.flock.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+58848
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+58848&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+58848&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+58848&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+58848&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+58848&report=yes&reason=non-english
Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+58848&report=yes&reason=already+in+docs
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+58848&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+58848&report=yes
Search -- http://master.php.net/manage/user-notes.php