How to run infinitely script in background on Linu

2019-04-04 22:23发布

问题:

I have a PHP script with infinite loop. I need this script running forever. So, I run

php /path/to/script.php > /dev/null &

And it works in background in my current user's security context. But when I close terminal window (log off), of course, CentOS Linux kills my program.

I see two guesses: run from a different user in background or make a daemon. I need help in each situation.

Thanks a lot!

回答1:

nohup is your friend.

nohup command &


回答2:

I think the general solution to that is nohup:

nohup is a POSIX command to ignore the HUP (hangup) signal, enabling the command to keep running after the user who issues the command has logged out. The HUP (hangup) signal is by convention the way a terminal warns depending processes of logout.

nohup is most often used to run commands in the background as daemons. Output that would normally go to the terminal goes to a file called nohup.out if it has not already been redirected. This command is very helpful when there is a need to run numerous batch jobs which are inter-dependent.



回答3:

nohup is your friend.



回答4:

You could:

  • Install screen and run the command from there. screen is a persistent terminal session that you can leave running.
  • Write an init/upstart (whatever you use) script so it loads on boot
  • Use the pear lib system_daemon
  • Use cron if batch work fits the scenario better (just remember to check for running instances before you launch another, iff concurrency is an issue)
  • Edit: or as everybody else and their brother has just said, nohup


回答5:

Using command

nohup your_command &

For example
nohup phantomjs highcharts-convert.js -host 127.0.0.1 -port 3003 &

here "phantomjs highcharts-convert.js -host 127.0.0.1 -port 3003" was my command