PHP Run Background Process using Exec


Hits: 9053  

If you need to start process in background and get its PID to manage it later using PHP.

<?php

function runInBackground($command,$log,$priority=0)
{
if($priority)
   $PID=shell_exec("nohup nice -n $priority $command > $log 2>&1 & echo $!");
else
   $PID=shell_exec("nohup $command > $log 2>&1 & echo $!");
return($PID);
}

?>
PHP Process
PHP Process

echo $! will return process ID
# Command & echo $!

 

Check if process is running

<?php

function isProcessRunning($PID)
{

if($PID==0)return false;
if($PID=="")return false;

exec("ps -p $PID 2>&1",$state);
return(count($state)>=2);

}

?>

 

Display Process Logs

<?php

function displayProcessLog($logfile)
{

exec('cat $logfile 2>&1',$log);
return implode("\r\n",$log);

}

?>

 

Kill Process

<?php

function killProcess($PID)
{
 exec('kill '.$PID.' 2>&1',$status);
 return implode("\r\n",$status);
}

?>

 

Save Process ID to file

#!/bin/bash
Command &
echo $! >/path/to/pid.file