Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run infinitely script in background on Linux?

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!

like image 664
Andrew Bashtannik Avatar asked Mar 23 '10 10:03

Andrew Bashtannik


People also ask

How do you keep a script running in the background Linux?

Running shell command or script in background using nohup command. Another way you can run a command in the background is using the nohup command. The nohup command, short for no hang up, is a command that keeps a process running even after exiting the shell.

How do I run a running script in the background?

Use bg to Send Running Commands to the Background You can easily send these commands to the background by hitting the Ctrl + Z keys and then using the bg command. Ctrl + Z stops the running process, and bg takes it to the background.


4 Answers

nohup is your friend.

nohup command &
like image 147
Andrew B Avatar answered Oct 05 '22 18:10

Andrew B


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.

like image 23
Pekka Avatar answered Oct 05 '22 17:10

Pekka


nohup is your friend.

like image 41
futureelite7 Avatar answered Oct 05 '22 17:10

futureelite7


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
like image 34
Oli Avatar answered Oct 05 '22 16:10

Oli