Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Command line script run in background goes in stopped state

I have a short php utility script, I run it from cli simply with:

php myscript.php

The script is always running, periodically performing some tasks (not relevant for the question). It doesn't need any input from the user. After running it, I usually press CTRL+z and then run bg to put the process in background, and everything is fine.

If I run it as:

php myscript.php &

the script is put on background on start, but it is also put in a stopped state. Example:

[1] 11513
[1]+  Stopped                 php myscript.php

even running bg at this point doesn't help, I have to run fg, then CTRL+z and bg again to make it work.

This is the php script:

<?
while(true){
    echo 'hi '.time()."\n";
    sleep(30);
}
?>

My problem is that I cannot run it directly in background, because the system stops it, and I don't understand why. How can I fix this?

update:

I made a bash version of the same script, and it can be run and put in background (running and not stopped) just by launching it with the & in the end (script.sh &)

script.sh:

#!/bin/bash
while true; do
    echo `date`
    sleep 30
done

Why the php script is being stopped after launching it in background, and the bash script doesn't? What could cause this different behaviour?

like image 412
Lorenzo Marcon Avatar asked Nov 30 '22 03:11

Lorenzo Marcon


1 Answers

I found what is causing the issue. In PHP, if the readline module is enabled, any command line script will expect an input, even if the script is written to NOT wait for user input.

To check if you have readline support enabled, just run:

php --info |grep "Readline Support"

and check the output. If you get Readline Support => enabled then you have readline enabled and you may experience the problem described in the original question.

The proper way to use the cli when is then to explicitly specify that php is not using the terminal for input:

php myscript.php < /dev/null &

Further info: http://php.net/manual/en/book.readline.php

Alternatives:

./test.php >/dev/null &    

or (more creative):

nohup php test.php > /dev/null 2>&1 &

(p.s.: I still believe this question belongs to ServerFault, btw.. problem solved!)

like image 89
Lorenzo Marcon Avatar answered Dec 04 '22 04:12

Lorenzo Marcon