Tipps und Tricks Filter
Mehrfachstart eines Scriptes verhindern
Werden PHP Scripte per Cron oder Kommandozeile gestartet, kann es von Vorteil sein zu verhindern, dass dieses mehrfach gestartet wird. Aber auch bei Scripten die per Browser aufgerufen werden bei längerer Laufzeit kann dies gewünscht sein. Es gibt einige Varianten dazu, besonders bei der Beachtung dieses je nach Betriebssystem zu tun. Hier mal eine Variante die unter Linux funktioniert.
<?php
//Locking POC
// Workaround
if ( !function_exists('sys_get_temp_dir')) {
function sys_get_temp_dir()
{
if ( !empty($_ENV['TMP']) ) { return realpath( $_ENV['TMP'] ); }
if ( !empty($_ENV['TMPDIR']) ) { return realpath( $_ENV['TMPDIR'] ); }
if ( !empty($_ENV['TEMP']) ) { return realpath( $_ENV['TEMP'] ); }
$tempfile = tempnam(uniqid(rand(),TRUE),'');
if ( file_exists($tempfile) ) {
unlink($tempfile);
return dirname($tempfile);
}
return '';
}
}
$tmpdir = realpath(sys_get_temp_dir());
$pid_file = $tmpdir.'lock.pid';
// Check if the file exists
if ( file_exists($pid_file) ) {
$pid = file_get_contents($pid_file);
if ( $pid !== false && (int)$pid > 0) {
// check the validity of the pid
if ( posix_kill($pid,0) ) {
// Process with pid is running
die('Script is already running!');
}
} else {
die('Error read the pidfile '.$pid_file);
}
}
$file = fopen($pid_file,'w+');
if ( !flock($file, LOCK_EX | LOCK_NB) ) {
die('Error to get exclusive lock on pidfile '.$pid_file);
}
// OK, now write own pid in pidfile
fwrite($file, getmypid());
//now the own program
// ...
//end
//kill the pidfile at the end
@unlink($pid_file);
?>
