Using nohup to keep a script running indefinitely

40,716

Solution 1

With nohup you must redirect also errors. The next command run script with output and errors redirecting to /dev/null:

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

But your script can be terminated by some other reasons (error in script, oom-killer, etc). So, you should daemonise it by system's init (if it support auto-restart - upstart, systemd, and some others can do it). Or you should write cron task for check and restart your script if it not run.

Solution 2

Perhaps you want to see what's going on and not redirect output to /dev/null.

I suggest you open a screen or tmux session. Both are terminal multiplexers, which will stay alive even if you log out.

E.g. (..) for info

$ screen
$(inside screen-t1): ./get_tweets.php
.... running first

Now press Ctrl-a c to open a new terminal.

 $(inside screen-t2): ./parse_tweets.php
 ... running second

Ctrl-a d lets you detach the session. When you log back on, use screen -r

Note: You can show a status bar in screen to visualize the different windows.

Solution 3

If you just want to make sure that your script restarts when it dies, you can do something like while true ; do php my_script.php ; done > /dev/null

This will wait for my_script.php to finish running, and then run it again. All output will be sent to /dev/null

If you want to use nohup, then you should do the following

$ echo 'while true ; do php my_script.php ; done > /dev/null' > ~/php_run_loop.sh
$ chmod a+x ~/php_run_loop.sh
$ nohup ~/php_run_loop.sh

NOTE: If you have an error or other problem in your php script, this will cause it to run over and over again without limit. This isn't a graceful solution, but it's a solution.

BTW, cron is good for running a short lived process on a schedule (every 5 minutes, or every week, etc), it doesn't know how to keep an existing process running.

Share:
40,716

Related videos on Youtube

Javacadabra
Author by

Javacadabra

Updated on September 18, 2022

Comments

  • Javacadabra
    Javacadabra over 1 year

    I am very new to Linux and I've only been using it to SSH to my web server using Putty. The issue I am having is this:

    Basically I've got 2 php scripts. One get_tweets.php constantly listens for tweets on twitters Streaming API whilst the other - parse_tweets.php logs these into a db. In order for these to work they've to be kept running continuously.

    I've been using the following commands to run them in the background and from what I've seen they run for most of the day, however whenever I log on to my computer in the morning the scripts have stopped and I've to run commands again.

    nohup php my_script.php > /dev/null &

    I'm just wondering if that is normal based on the commands I am using, should they run indefinitely when using nohup and if not what is the alternative? A CRON job?

    Thanks for the help