. */ /** * This file contains the File mutex implementation. * * @author Dinu Florin * @package Core * @subpackage Mutex */ require_once 'MutexInterface.class.php'; /** * File mutex class. * * @author Dinu Florin * @package Core * @subpackage Mutex */ class FileMutex implements MutexInterface { protected $fileName = null; //The lock file. protected $file = null; //The file pointer. protected static $dir = null; //The directory where we store the lock files. /** * @see MutexInterface::canInstantiate() */ public static function canInstantiate() { return function_exists('flock'); //It will return true in every normal case. } /** * Constructor. * * @see MutexInterface::__construct() */ public function __construct($name) { //Check the temp dir if(is_null(self::$dir)) { self::$dir = Util::getTempDir().DIRECTORY_SEPARATOR.'locks'; if(!file_exists(self::$dir)) { if(!@mkdir(self::$dir) && !file_exists(self::$dir)) { throw new MutexException("Failed to create lock directory {self::$dir}"); } } } $this->fileName = self::$dir.DIRECTORY_SEPARATOR.md5($name).'.lock'; touch($this->fileName, time()); } /** * Lock the mutex. * * @see MutexInterface::lock() */ public function lock() { $this->file = fopen($this->fileName, 'r'); if($this->file === false) { throw new MutexException("Error opening lock file {$this->fileName}"); } if(!flock($this->file, LOCK_EX)) { throw new MutexException("Error locking mutex"); } } /** * Unlock the mutex. * * @see MutexInterface::unlock() */ public function unlock() { if(!flock($this->file, LOCK_UN)) { throw new MutexException("Error unlocking mutex"); } fclose($this->file); } } ?>