php exec command (or similar) to not wait for result

greg picture greg · Sep 29, 2010 · Viewed 102.8k times · Source

I have a command I want to run, but I do not want PHP to sit and wait for the result.

<?php
echo "Starting Script";
exec('run_baby_run');
echo "Thanks, Script is running in background";
?>

Is it possible to have PHP not wait for the result.. i.e. just kick it off and move along to the next command.

I cant find anything, and not sure its even possible. The best I could find was someone making a CRON job to start in a minute.

Answer

Cristian picture Cristian · Sep 29, 2010

From the documentation:

In order to execute a command and have it not hang your PHP script while
it runs, the program you run must not output back to PHP. To do this,
redirect both stdout and stderr to /dev/null, then background it.

> /dev/null 2>&1 &

In order to execute a command and have
it spawned off as another process that
is not dependent on the Apache thread
to keep running (will not die if
somebody cancels the page) run this:

exec('bash -c "exec nohup setsid your_command > /dev/null 2>&1 &"');