[Tutor] how to run a process forever

Steve Willoughby steve at alchemy.com
Wed Dec 10 20:29:10 CET 2008


On Wed, Dec 10, 2008 at 01:15:18PM -0600, shawn bright wrote:
> Sorry, was not very specific in my request.
> 
> say i have a script like
> 
> while 1:
>     do_something_cool()
>     time.sleep(2)

Ah, ok.  First of all, my preference would be to say "while True:"
there, seems more clear to me.  A more complex program might have
different "do this forever" logic, but an infinite loop is pretty
common as well.

The sleep is a very important step for making sure that the script
doesn't spin forever.  Better would be to sleep as long as practical,
or wake up on some event (assuming you don't just need this to run
something every set interval of time).

> i am running this on a linux computer. How would i check that it is
> running? (from cron part)

Typically you have your program write its PID to a file.  The cron
script can check that file and see if that process is still alive before
deciding to start another.

Or, you could just look at the processes and look for your script by
name.

Or any of a few other semaphore kinds of things (a file your script
touches periodically, and if it's more than n minutes old is a sign
your script has locked up/died is one simple example).

> and how do i kick it off when i boot the computer? ( the init script part)

Unix-like systems have a script run when the system is booted.  BSD
systems usually put this is /etc/rc.local.  Linux usually has a 
directory of scripts, one per application, in /etc/init.d, with symlinks
from /etc/rc<n>.d indicating which run level <n> you want that service
started.  See your distro's documentation for details specific to your
flavor of Linux.

You'll want to run it in the background without any associated terminal.
In a Bourne-type shell, this usually looks like this:

     /path/to/myscript </dev/null >/dev/null 2>&1 &

-- 
Steve Willoughby    |  Using billion-dollar satellites
steve at alchemy.com   |  to hunt for Tupperware.


More information about the Tutor mailing list