I need to open a log file for writing. The problem is that a lot can do this at the same time, and I don't want conflicts. Each record will be a single line, usually around 150 bytes (and always less than 1K), and getting things in chronological order is strictly not required.
I think I want to try flock(), and if it doesn't work, keep trying for a few seconds. If the lock cannot be set after several attempts, release it.
$fh=fopen($logfile, "a");
if (flock($fh, LOCK_EX|LOCK_NB)) {
$locked=TRUE;
} else {
$locked=FALSE;
// Retry lock every 0.1 seconds for 3 seconds...
$x=0; while($x++ < 30) {
usleep(100000);
if (flock($fh, LOCK_EX|LOCK_NB)) {
$locked=TRUE;
break;
}
}
}
if ($locked) {
if (fwrite($fh, strftime("[%Y-%m-%d %T] ") . $logdata . "\n")) {
print "Success.\n";
} else {
print "Fail.\n";
}
flock($fh, LOCK_UN)
} else {
print "Lock failed.\n";
}
, . -, - (do...while ..), , PHP? -, PHP? (, , .)
, , syslog(), PHP-, , , (.. /etc/syslog.conf) .
UPDATE: |LOCK_NB , randy .