note 58620 deleted from function.flock by danbrown
| From: | danbrown@php.net | Date: | Mon, 18 May 2009 00:41:10 +0000 |
| Subject: | note 58620 deleted from function.flock by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-155413@lists.php.net to get a copy of this message | ||
Note Submitter: relsqui at chiliahedron dot com
----
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!";
}
?>