1

I'm trying to run in background two bash command using exec function.

 $action[] = "/path/script1 par1 > log1 2>&1";
 ...
 $action[] = "/path/script2 par2 > log2 2>&1";
 ...
 $cmd = "( " .implode(' && ',$action). " ) &";
 exec($cmd);

script1 and script2 are bash scripts.

Scripts are properly executed and their output is correctly saved in their log files, but my application hangs. It seems that last & doesn't work.

I have already tried:

 $cmd = "bash -c \"" .implode(' && ',$action). "\" &";

If I run a single command, it works in background.

I captured $cmd and if I run:

 ( /path/script1 par1 > log1 2>&1 && /path/script2 par2 > log2 2>&1 ) &

from command line, it works in background.

I'm using Apache/2.0.52 and PHP/5.2.0 on Red Hat Enterprise Linux AS release 3 (Taroon Update 2)

1 Answer 1

1

The answer is hidden in the PHP exec documentation:

If a program is started with this 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.

Add a redirection to the top level of your command line:

exec( "bash -c \"( ./script1 par1 > log1 2>&1 && ./script2 par2 > log2 2>&1 ) \" >/dev/null 2>&1 & " );

and without bash -c:

exec( "( ./script1 par1 > log1 2>&1 && ./script2 par2 > log2 2>&1 ) >/dev/null 2>&1 & " );

Tested with PHP 5.3.3-7 (command line invocation): Program hangs before adding the redirect operators, and terminates afterwards.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.