0

I have a bash script with a few lines similar to the following

echo "Do something"
/bin/sh -c 'echo $$>pidfile && exec "command"' &
echo "Ran Command">/path/to/outputfile.txt
exit 0

Then I call that from a PHP script
return shell_exec("/path/to/bash/script arguments");

Now, when I do that, the command is run successfully, and outputfile.txt contains "Ran Command".

However, the PHP script times out after 10ish seconds. The bash script takes about 2-3 seconds to run

If I change the line to return shell_exec("/path/to/bash/script arguments >/dev/null 2>&1");

Then it executes and the PHP script doesn't time out.

I understand why redirecting the output lets PHP continue executing, but I can't figure out why PHP is timing out in the first place requiring me to do that. Can someone give me some assistance with this?

11
  • The bin/sh should use 2>&1 & instaed of & only, because you are moving the script into the background, but the outpu is still piped whitin the bash script. maybe PHP waits vor stdin/stderr to close. Commented Sep 2, 2016 at 14:34
  • If that was the case, shouldn't the same timeout (or apparent hang) occur if I manually run /path/to/bash/script arguments? It doesn't. Only when I run that through php's shell_exec() does the time out happen. Commented Sep 2, 2016 at 14:35
  • >/dev/null 2>&1 & look here unix.stackexchange.com/questions/70963/… Commented Sep 2, 2016 at 14:36
  • the same timeout maybe you will not see an output, but the /bin/sh can still be running. check this with htop or ps -Af Commented Sep 2, 2016 at 14:37
  • @JustOnUnderMillions I was using the >/dev/null part, I knew you meant that. Is there any reason to put it in the bash script rather than the PHP script? Commented Sep 2, 2016 at 14:54

1 Answer 1

2

Test this two versions and you get it:

test1.sh /bin/sh -c 'sleep 10' >/dev/null 2>&1 &

test2.sh /bin/sh -c 'sleep 10' &

run both with php on command line like

test1.php <?php shell_exec('test1.sh');

test2.php <?php shell_exec('test2.sh');

and see the difference.

test2.sh is taking 10ish seconds and test1.sh is working like your

return shell_exec("/path/to/bash/script arguments >/dev/null 2>&1");

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

1 Comment

It does work and I'll mark this as the solution (I'll put the >/dev/null 2>&1 part in the bash script), but I'm still a bit at a loss. Running those under PHP they do behave differently. However, in bash, ./test1.sh and ./test2.sh execute exactly the same,

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.