note 45614 deleted from function.flock by danbrown

From: Date: Mon, 18 May 2009 00:44:50 +0000
Subject: note 45614 deleted from function.flock by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-155423@lists.php.net to get a copy of this message
Note Submitter: rehfeld.us ---- This is based on the function by jeroenl at see dot below and the suggestion of jeppe at bundsgaard dot net please note this wont work on windoes unless using php5, due to the use of usleep() one may wish to tailor some of the values to better suit thier application. the rand() values, the number of loop attempts, and the max age of the lockfile are what im referring to <?php function locked_filewrite($filename, $data) { ignore_user_abort(1); $lockfile = $filename . '.lock'; // if a lockfile already exists, but it is more than 5 seconds old, // we assume the last process failed to delete it // this would be very rare, but possible and must be accounted for if (file_exists($lockfile)) { if (time() - filemtime($lockfile) > 5) unlink($lockfile); } $lock_ex = @fopen($lockfile, 'x'); for ($i=0; ($lock_ex === false) && ($i < 20); $i++) { clearstatcache(); usleep(rand(9, 999)); $lock_ex = @fopen($lockfile, 'x'); } $success = false; if ($lock_ex !== false) { $fp = @fopen($filename, 'a'); if (@fwrite($fp, $data)) $success = true; @fclose($fp); fclose($lock_ex); unlink($lockfile); } ignore_user_abort(0); return $success; } ?>

« previous php.notes (#155423) next »