Is there a way to use shell_exec without waiting for the command to complete?

04/19/2020 06:30:01

I have a process intensive task that I would like to run in the background.

The user clicks on a page, the PHP script runs, and finally, based on some conditions, if required, then it has to run a shell script, E.G.:

shell_exec('php measurePerformance.php 47 844 [email protected]');

Currently I use shell_exec, but this requires the script to wait for an output. Is there any way to execute the command I want without waiting for it to complete?

Verified Answer (148 Votes)

06/20/2009 02:27:34

How about adding.

"> /dev/null 2>/dev/null &"

shell_exec('php measurePerformance.php 47 844 [email protected] > /dev/null 2>/dev/null &');

Note this also gets rid of the stdio and stderr.


Answer #2 (28 Votes)

06/20/2009 02:32:31

This will execute a command and disconnect from the running process. Of course, it can be any command you want. But for a test, you can create a php file with a sleep(20) command it.

exec("nohup /usr/bin/php -f sleep.php > /dev/null 2>&1 &");

Answer #3 (11 Votes)

05/14/2013 20:03:51

You can also give your output back to the client instantly and continue processing your PHP code afterwards.

This is the method I am using for long-waiting Ajax calls which would not have any effect on client side:

header("Connection: close");
echo json_encode($out);
header("Content-Length: " . ob_get_length());
// execute your command here. client will not wait for response, it already has one above.

You can find the detailed explanation here:

Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.