note 86053 deleted from function.flock by danbrown

From: Date: Mon, 18 May 2009 00:33:29 +0000
Subject: note 86053 deleted from function.flock by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-155387@lists.php.net to get a copy of this message
Note Submitter: please help please ---- regarding race conditions (as they might apply to files or anything else)... i find it useful to implement a process queue: <?php function queue_begin($myprocess = "", $mytimeout = 0) { $keepalive = 60; $starttime = time(); $begin_return = false; if (file_exists("queues/" . $myprocess . ".dat")) { while ((file_exists("queues/" . $myprocess . ".dat")) && ((time() - $starttime) < $mytimeout)) { if (filemtime("queues/" . $myprocess . ".dat") < (time() - $keepalive)) { // delete old process unlink("queues/" . $myprocess . ".dat"); } else { usleep(100000); } } } if (!file_exists("queues/" . $myprocess . ".dat")) { // create process $pid = fopen("queues/" . $myprocess . ".dat", "w"); fclose($pid); $begin_return = true; } return $begin_return; } function queue_end($myprocess = "") { if (file_exists("queues/" . $myprocess . ".dat")) { // delete process unlink("queues/" . $myprocess . ".dat"); } } if (queue_begin()) { // this will run alone, one instance at a time. doesn't matter how you got here, by command-line or httpd process, or on this operating system or that, or anything else. queue_end(); } else { echo "timed out and failed to queue process"; } ?> if your script does many things which should be queue'd, and not all of them run all of the time, pass a unique string along with queue_begin() and queue_end() to specify precisely which thing you're trying to queue. that way, you can read-write your session file while another process read-writes your guestbook file, and these things don't need to wait on each other (though session read-writes would need to wait on other session read-writes and guestbook read-writes would need to wait on other guestbook read-writes). should the disasterous scenario occur that your process file is erroneously left in existence, everything will be ok again after [keepalive] seconds. therefore, nothing should run between queue_begin() and queue_end() which takes longer than [keepalive] seconds. this mostly applies to processes which are only carried out by php. that is, this code offers no protection against notepad's potential to corrupt your session file - but then again, neither does flock() or anything else.

« previous php.notes (#155387) next »