Tuesday, February 21, 2012

PHP exec() function hangs when running external program in the background

Well, this was a case of not reading the PHP documentation, because it clearly states that:

"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."

So, normally when you run a program with exec(), it finishes it's normal execution and you're good, but if you are trying to run something in the background (like creating an ssh tunnel in my case) you need to redirect it's output (stdout and stderr) to another file.

I solved it by adding this to my command:

> /dev/null 2>&1 &

Which redirects stdout to /dev/null and then redirects stderr to stdout (which goes to /dev/null) and then telling the command to run in the background with the ampersand.

Done ! exec() doesn't hang anymore ;-)

Carlos

No comments:

Followers

About me

Santa Fe, Argentina
Programador Web, PHP, MySQL, JQuery, Administrador Linux. LAMP, Lighttpd, Nginx.