Bagaimana Cara Menjalankan Background Process di PHP ?

Anda dapat membaca referensi [1], dan untuk penjelasan input/output redirection dapat melihat referensi [2].

Berikut adalah salah satu contoh fungsi hasil modifikasi dari [1] untuk menjalankan sebuah perintah di background dan meredirect STDOUT dan STDERR normal ke sebuah file, agar nanti kita dapat memantau progress dari sebuah perintah, apakah sudah selesai atau belum.


public static function run_in_background($Command, $Priority = 0, $log_file)

{

$root_dir = sfConfig::get('sf_root_dir');

$user_id = sfContext::getInstance()->getUser()->getGuardUser()->getId();

$the_log_file = $root_dir.DIRECTORY_SEPARATOR.'log'.DIRECTORY_SEPARATOR.$user_id."_".str_replace(" ","_",$log_file).".log" ;

if($Priority) {

$PID = shell_exec("nohup nice -n $Priority $Command > $the_log_file 2>&1 & echo $!");

} else {

$PID = shell_exec("nohup $Command > $the_log_file 2>&1 & echo $!");

}


return($PID);

}

Referensi