0
votes

I'm aware that we can run background process with the following:

exec("doTask.php $arg1 $arg2 $arg3 >/dev/null 2>&1 &");

(Taken from: Run PHP Task Asynchronously)

However I have a script that depends on the status of the first execution. Example:

mongoexport ... | awk ... > my.csv && zip myzip my.csv

The CSV file must exists before it can zip.
Update: filename and a few query conditions are user submitted values.

So I have something like:

exec("mongoexport ... | awk ... > my.csv && zip myzip my.csv > /dev/null 2>&1 &);

But that doesn't work. PHP hangs there waiting for the script to finish running.

I tried

exec("mongoexport ... | awk ... > my.csv &);

That works.

So is && the reason it doesn't run in background?
How can I make the example run in background?

1
Any chance you can make it into a shell script and run that shell from PHP? - Passerby
I should add that the shell command takes params submitted by the users. For example the filename is user specified. So no shell script I guess. - resting
I'm not sure about UNIX shell, but in Win32 bat, you can use %1, %2, etc. or directly %s to pass params, so if my.csv and myzip is the params user submitted, maybe you can make command shell.sh my.csv myzip > /dev/null 2>&1 & and in shell mongoexport... %1 && %2 or something like that. - Passerby
I think I could pass the variables as arguments to the shell script. Thanks. I'll keep that as the last resort if there are no better ways of doing it. - resting

1 Answers

1
votes

The following will work

exec("(mongoexport ... | awk ... > my.csv && zip myzip my.csv) > /dev/null 2>&1 &")

It tells the shell to run all the sequence of commands enclosed in braces in the background process and redirect the output, so the exec function has nothing to wait for.

In your example, the shell launched from exec waited for the awk to finish and after that ran zip in background (if awk exited with status 0)