Skip to content
Advertisement

PHP Calling shell_exec on a bash script running a background process times out

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?

Advertisement

Answer

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");

Advertisement