Using Shell command we can run a PHP script known as child process inside another PHP script known as Parent process without allowing the parent process to wait for the completion of the child process.
This is mostly useful for running crons in background where the parent process calling the cron will not wait for process to complete, but rather instantly jump the the next line of code.
On Linux systems, we can easily call another PHP script via the shell, set it to run off in the background and send its output to /dev/null using the code below.
system(‘php ‘.$path.’test_monthly_cron_manually.php >/dev/null >&- >/dev/null &’);
Where $path = absolute paths for the command line and the working page.
test_monthly_cron_manually.php = name of the php file(child process) that you want to run in the background
We can pass arguments to the background process using the code below.
system(‘php ‘.$path.’test_monthly_cron_manually.php ‘.$arg1 ‘.$arg2.’ >/dev/null >&- >/dev/null &’);
When we pass arguments through shell command we can get these parameters in the child process as
$arg2 = $argv
Note: Its actually the ‘&’ which tells a job to run in the background on linux, the > /dev/null just sends the output of the command to a black hole. So, when we send the output to /dev/null, we are simply destroying it.
While implementing this process we should look into the following points to make the script Run.
* We need to give the absolute path correctly.
* We need to set up permissions correctly to allow the php command line to run the child process that means if the child process is inside a folder then we need to set Read/Write permission on the folder.
* The above code only work for linux/debian.