A python program as a Win "Service" or Unix "Daemon"?

Ben Caradoc-Davies bmcd at es.co.nz
Thu Mar 16 15:09:33 EST 2000


On Thu, 16 Mar 2000 17:14:30 +0100, Alessandro Bottoni 
<Alessandro.Bottoni at think3.com> wrote:
>Is there any way to install a Python program as a Unix Daemon or a Windows
>Service? (Together with an instance of the interpreter, of course..)

For Unix:

As far as a Unix kernel is concerned, a Python script ("script" meaning a
program which is recognised by the #! magic number) is just the same as any
other executable.

What are you trying to do? You can have inetd or tcpd run the process (as an
ordinary filter, then it just gets started whenever anyone connects to it (one
process per connection). You don't need a daemon for this.

A true Unix daemon is just any ordinary program which detaches itself from it's
controlling terminal and it's group through the following steps (see the Unix
programming FAQ):
fork(), parent exits
setsid() (to become process group leader ... man 3 setsid)
fork(), parent exits, now child process is adopted by init
close all file descriptors
chdir to root directory (so as to not prevent the unmounting of other volumes).

All of this functionality is available in Python (mainly through the os
module).

If you have a daemon called command, and you type
  command
at the shell prompt, it immediately returns, but a copy of your daemon is now
running. If you want your daemon to run as root, and be started automatically
at startup, just put the command in your startup scripts.

>Is there any module to help the programmer to develop this kind of
>applications?

# Here's a snippet of a tiny module I wrote a while ago ...
# Call the module Daemon.py
# Under Unix, Daemon.daemon() will turn the process into daemon.
# Version 0.0.0
# Copyright Ben Caradoc-Davies <bmcd at es.co.nz>, June 1999.
# Distribute under GNU General Public License v2 or later.
 
import os
import sys

def daemon( umask=077, chdir="/" ):

  def fork_and_die():
    r = os.fork()
    if r == -1:
      raise OSError, "Couldn't fork()."
    elif r > 0:  # I'm the parent
      sys.exit(0)
    elif r < 0:
      raise OSError, "Something bizarre happened while trying to fork()."
    # now only r = 0 (the child) survives.

  fork_and_die()
  os.setsid()
  fork_and_die()
  os.chdir(chdir)
  os.umask(umask)
  sys.stdin.close()
  sys.stdout.close()
  sys.stderr.close()

### End of Daemon.py fragment

-- 
Ben Caradoc-Davies <bmcd at es.co.nz>



More information about the Python-list mailing list