| Newsgroups |
php.notes |
| Message-ID |
<[email protected]> |
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.
----
Server IP: 69.147.83.197
Probable Submitter: 72.201.135.178
----
Manual Page -- http://www.php.net/manual/en/function.flock.php
Edit -- https://master.php.net/note/edit/86053
Del: integrated -- https://master.php.net/note/delete/86053/integrated
Del: useless -- https://master.php.net/note/delete/86053/useless
Del: bad code -- https://master.php.net/note/delete/86053/bad+code
Del: spam -- https://master.php.net/note/delete/86053/spam
Del: non-english -- https://master.php.net/note/delete/86053/non-english
Del: in docs -- https://master.php.net/note/delete/86053/in+docs
Del: other reasons-- https://master.php.net/note/delete/86053
Reject -- https://master.php.net/note/reject/86053
Search -- https://master.php.net/manage/user-notes.php