note 90254 deleted from function.flock by danbrown
| From: | danbrown@php.net | Date: | Mon, 18 May 2009 00:32:04 +0000 |
| Subject: | note 90254 deleted from function.flock by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-155386@lists.php.net to get a copy of this message | ||
Note Submitter: wernerdegroot at gmail dot com
----
This does the same as flock(), only returns immediately:
<?php
define("EXCLUSIVE_LOCK", 0);
define("SHARED_LOCK", 1);
define("LOCK", 0);
define("UNLOCK", 2);
define("ADD", 1);
define("SUBSTRACT", -1);
function createLock($fileName) {
$lockDir = "$fileName~";
return @mkdir($lockDir);
} // createLock
function removeLock($fileName) {
$lockDir = "$fileName~";
if(is_dir($lockDir)) {
rmdir($lockDir);
} // if
return true;
} // removeLock
function updateLockFile($fileName, $operation) {
$lockDir = "$fileName~";
$sharedLockFile = "$lockDir/shared";
$exclusiveLockDir = "$lockDir/exclusive";
while(!file_exists($sharedLockFile)) {
if(is_dir($exclusiveLockDir)) {
return false;
}
usleep(10000);
} // while
do {
$locked = !(createLock($sharedLockFile));
if($locked) {
usleep(10000);
} // if
} while($locked);
$handle = fopen($sharedLockFile, "r+b");
$lockNumber = ord(fgetc($handle));
if($lockNumber == 1 && $operation == SUBSTRACT) {
fclose($handle);
unlink($sharedLockFile);
removeLock($sharedLockFile);
rmdir($lockDir);
return;
}
fseek($handle, 0);
fwrite($handle, chr($lockNumber + $operation));
fclose($handle);
removeLock($sharedLockFile);
return true;
} // updateLockFile
function lockFile($fileName, $operation) {
$lockDir = "$fileName~";
$exclusiveLockDir = "$lockDir/exclusive";
$sharedLockFile = "$lockDir/shared";
if($operation == UNLOCK) {
if(is_dir($lockDir)) {
if(is_dir($exclusiveLockDir)) {
rmdir($exclusiveLockDir);
rmdir($lockDir);
} else {
updateLockFile($fileName, SUBSTRACT);
} // if
}
return true;
} // if
$locked = !(@mkdir($lockDir));
if($locked) {
if($operation == EXCLUSIVE_LOCK) {
return false;
} else {
return updateLockFile($fileName, ADD);
return true;
} // if
} else {
if($operation == EXCLUSIVE_LOCK) {
mkdir($exclusiveLockDir);
} else {
createLock($sharedLockFile);
touch($sharedLockFile);
$handle = fopen($sharedLockFile, "wb");
fwrite($handle, chr(1));
fclose($handle);
removeLock($sharedLockFile);
} // if
return true;
} // if
} // lockFile
echo lockFile("a.txt", UNLOCK) ? "gelukt" : "mislukt";
?>