tags:

views:

97

answers:

3

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.

+1  A: 

You can run the command in the background by adding a & at the end of it as:

exec('run_baby_run &');

But doing this alone will hang your script because:

If a program is started with exec function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

So you can redirect the stdout of the command to a file, if you want to see it later or to /dev/null if you want to discard it as:

exec('run_baby_run > /dev/null &');
codaddict
that worked great, thank you for your help.
greg
+5  A: 

It's always good to check the documentation:

In order to execute a command have 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 &"');

Cristian
thanks, but for the life of me even now with hindsight, I would not have gotten that fro mthe doco. Thanks
greg
+1  A: 

If you have to do this frequently, you might also be interested in a JobQueue, like Gearman.

Gordon