Ich versuche, eine Funktion zu erstellen (zum Zwecke der Protokollierung)
append($file, $data)
das
- schafft
$file
wenn es nicht existiert und - atomar anhängt
$data
dazu.
Es muss
- hohe Parallelität unterstützen,
- lange Saiten unterstützen und
- so leistungsfähig wie möglich sein.
Bisher ist der beste Versuch:
function append($file, $data)
{
// Ensure $file exists. Just opening it with 'w' or 'a' might cause
// 1 process to clobber another's.
$fp = @fopen($file, 'x');
if ($fp)
fclose($fp);
// Append
$lock = strlen($data) > 4096; // assume PIPE_BUF is 4096 (Linux)
$fp = fopen($file, 'a');
if ($lock && !flock($fp, LOCK_EX))
throw new Exception('Cannot lock file: '.$file);
fwrite($fp, $data);
if ($lock)
flock($fp, LOCK_UN);
fclose($fp);
}
Es funktioniert OK, aber es scheint ziemlich komplex zu sein. Gibt es einen saubereren (integrierten?) Weg, dies zu tun?