hpekristiansen
hpekristiansen

Reputation: 1070

why is PHP hanging, when a bash call forks

I am calling some bash code from php, but even though I fork the bash (with &), the php will not finish before the full bash is done.

This code:

<html>
<body>
HTML START<br>
<pre>
<?php
echo "PHP START\n";
echo `sleep 30 &`;
echo "PHP END\n";
?>
</pre>
HTML END<br>
</body>
</html>

Will not show anything in the browser, before after 30 seconds.

What I really want is to start a GUI app from php, that should continue to run.

Upvotes: 4

Views: 284

Answers (5)

cypherabe
cypherabe

Reputation: 2603

what you probably want to do is seperate the forked processes. One way to do this is using nohup in the bash command.

for examples look at the user comments on php.net > exec, especially this one: http://www.php.net/manual/en/function.exec.php#88704

be carefull, though, you lose direct feedback and have to monitor your processes/results through other means

Upvotes: 0

Charles Duffy
Charles Duffy

Reputation: 295315

Close all file descriptors in your sleep call to allow it to detach:

<?php
echo "PHP START\n";
echo `sleep 30 <&- 1<&- 2<&- &`;
echo "PHP END\n";
?>

Otherwise, the output file descriptor is still open, and PHP is still trying to wait to receive its output, even with the process no longer attached directly.

This works correctly when run, immediately exiting but leaving a sleep process behind:

$ time php5 test.php; ps auxw | grep sleep | grep -v grep
PHP START
PHP END

real    0m0.019s
user    0m0.008s
sys         0m0.004s
cduffy    6239  0.0  0.0  11240   576 pts/0    S    11:23   0:00 sleep 30

Upvotes: 3

johniek_comp
johniek_comp

Reputation: 322

sleep(30);

mast be...

<?php
echo "PHP START\n";
echo sleep(30);
echo "PHP END\n";
?>

Upvotes: -1

Maxime Pacary
Maxime Pacary

Reputation: 23021

Maybe create another HTTP process by using an Ajax call to another PHP script, which task will be to launch asynchronously your sleep 30 command, or whatever you want, on the server.

Upvotes: 0

rollstuhlfahrer
rollstuhlfahrer

Reputation: 4078

PHP waits for the called process to terminate even if the amperstand is explicit given

Upvotes: 1

Related Questions