note 45614 added to function.flock

From: Date: Mon, 13 Sep 2004 02:48:20 +0000
Subject: note 45614 added to function.flock
Groups: php.notes 
Request: Send a blank email to php-notes+get-76573@lists.php.net to get a copy of this message
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; } ?> ---- Manual Page -- http://www.php.net/manual/en/function.flock.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+45614 Delete -- http://master.php.net/manage/user-notes.php?action=delete+45614&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+45614&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#76573) next »