I would like to daemonize a php script (Jobque.php) under PHP 5.3 in Linux
The idea is to call the script like this:
php -f ./application/Model/Jobque.php start
and than the script would do a shell_exec to put itself in the background and do the processing like this
nohup php -f /var/.../application/Model/Jobque.php process 2> /dev/null & echo $!
this last command indeed starts the script in the background and all is fine, however when I issue this command from within the script itself the script waits until the execution stops (never)
this is the function I use to start the script as a daemon – the Windows part works
public function start_daemon() {
if (file_exists ( $this->pidfile ))
die ( 'process is already running - process pidfile already exists -> ' . $this->pidfile );
$cmd = 'php -f ' . __FILE__ . ' process';
if (substr ( php_uname (), 0, 7 ) == "Windows") {
$WshShell = new COM ( "WScript.Shell" );
$oExec = $WshShell->Run ( "$cmd /C dir /S %windir%", 0, false );
exec ( 'TASKLIST /NH /FO "CSV" /FI "imagename eq php.exe" /FI "cputime eq 00:00:00"', $output );
$output = explode ( '","', $output [0] );
$pid = $output [1];
file_put_contents ( $this->pidfile, $pid );
} else {
$execstr = "nohup $cmd 2> /dev/null & echo $!";
//echo $execstr; -- the execstr is right in itself
$PID = shell_exec ( $execstr );
//echo $PID; -- we never get here
file_put_contents ( $this->pidfile, $PID );
}
echo ('JobQue daemon started with pidfile:' . $this->pidfile);
}
what am I doing wrong here, and how to do it right?
I ended up using pcntl_fork for daemonizing the script under Linux, like this: