note 58620 added to function.flock
| From: | relsqui at chiliahedron dot com | Date: | Wed, 09 Nov 2005 23:43:42 +0000 |
| Subject: | note 58620 added to function.flock | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-98349@lists.php.net to get a copy of this message | ||
Well, I can claim I wrote this as a workaround for earlier versions of PHP, but in reality I just
didn't think to look up flock() until after I'd written it. However, if you do happen to
have an earlier version of PHP, these might come in handy. Enjoy.
<?php
// Lock a file, timing out if it takes too long.
function lock ($lock, $tries) {
$lock0 = ".{$lock}0";
$lock1 = ".{$lock}1";
for ($i=0; $i<$tries; $i++) {
if (!is_file($lock0)) {
touch($lock0);
if (!is_file($lock1)) {
touch($lock1);
return 1;
}
}
usleep(100);
}
return 0;
}
// Unlock a file.
function unlock ($lock) {
unlink(".{$lock}1");
unlink(".{$lock}0");
}
// Usage example.
$filename = "somefile";
$data = "stuff and things\n";
$tries = 10;
if (lock($filename, $tries)) {
$h = fopen($filename, "a") or die();
fwrite($h, $data);
fclose($h);
unlock($filename);
} else {
die("Failed to lock $filename after " . ($tries*100) . " milliseconds!";
}
?>
----
Manual Page -- http://www.php.net/manual/en/function.flock.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+58620
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+58620&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+58620&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+58620&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+58620&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+58620&report=yes&reason=non-english
Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+58620&report=yes&reason=already+in+docs
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+58620&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+58620&report=yes
Search -- http://master.php.net/manage/user-notes.php