[Tutor] Python Daemon

Michael P. Reilly arcege@shore.net
Sun, 11 Mar 2001 19:39:55 -0500 (EST)


> Hello:
>   I'd like to write a test python script as a daemon.
> (Red Hat 6.0)
> If the topic is a little involved, (and I'm sure it is),
> I'd be perfectly happy if someone could just point
> me to some documentation to get me started.
> TIA
> Regards
> --
> Tim Johnson

You'll have to say which platform you are working with.  On WinNT, they
are called "services" (as in IIS, Internet Information Service).  The
"Python Programming on Win32" book covers this pretty well, but I'm no
windoze programmer.  Since you're calling this a "daemon", I asusme you
are asking for UNIX.

On UNIX, a daemon is a process without an associated terminal or login
shell.  Backgrounding a process from a shell is not enough, it must
disassociate itself from the controlling terminal as well (and not be
affected by the user shell).  Run the os.setpgrp() function, and close
stdin, stdout and stderr.

Some example code is (based on Steven's "daemon_start()" function):
import os, signal, sys
def make_daemon():
  if os.getppid() != 1:  # we're already a daemon (started from init)
    if hasattr(signal, 'SIGTTOU'):
      signal.signal(signal.SIGTTOU, signal.SIG_IGN)
    if hasattr(signal, 'SIGTTIN'):
      signal.signal(signal.SIGTTIN, signal.SIG_IGN)
    if hasattr(signal, 'SIGTSTP'):
      signal.signal(signal.SIGTSTP, signal.SIG_IGN)
    pid = os.fork()
    if pid:
      sys.exit(0)
    os.setpgrp()
    signal.signal(signal.SIGHUP, signal.SIG_IGN)
  sys.stdin.close()
  sys.stdout.close()
  sys.stderr.close()
  os.chdir(os.sep)
  os.umask(0)
  signal.signal(signal.SIGCLD, signal.SIG_IGN)

if __name__ == '__main__':
  make_daemon()

Good luck,
  -Arcege

-- 
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager  | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------