Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php background process using exec function

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.

like image 792
Aliweb Avatar asked Oct 11 '12 15:10

Aliweb


People also ask

Does PHP wait for exec to finish?

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.

How does PHP exec work?

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");

How do I run a PHP script continuously?

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.

What is Shell_exec?

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.


1 Answers

You have to reroute programs output somewhere too, usually /dev/null

exec($cmd . " > /dev/null &");
like image 70
ninaj Avatar answered Oct 05 '22 01:10

ninaj