I have searched a lot to find the exact answer but didn't find any.
many people mentioned that we should & at end of command to don't wait for response.
for example to run bg.php in background , this was recommended:
exec("/usr/bin/php bg.php &");
but it doesn't work for me. and the main script waits for complete execution of the bg.php.
I also read somewhere to write bg.php output in a logfile but my background script doesn't produce any output. It does some process and then write something in database.
I just want my script to run bg.php and don't wait for it to end.
please help me including correct code.
PHP exec will wait until the execution of the called program is finished, before processing the next line, unless you use & at the end of the string to run the program in background.
The exec() function runs an external program, specified in the first parameter. It sends back the last line outputted from that program as its return value, unlike passthru() , which prints out all the output the program generates. print exec("uptime");
You can put a task (such as command or script) in a background by appending a & at the end of the command line. The & operator puts command in the background and free up your terminal. The command which runs in background is called a job. You can type other command while background command is running.
The shell_exec() function is an inbuilt function in PHP which is used to execute the commands via shell and return the complete output as a string. The shell_exec is an alias for the backtick operator, for those used to *nix. If the command fails return NULL and the values are not reliable for error checking.
You have to reroute programs output somewhere too, usually /dev/null
exec($cmd . " > /dev/null &");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With