running a daemon in python

rishi pathak mailmaverick666 at gmail.com
Tue Feb 26 02:06:12 EST 2008


Use the function goDaemon just before starting the server loop:

###############Begin Module#######################
import os
import sys
# Default daemon parameters.
# File mode creation mask of the daemon.
UMASK = 0
# Default working directory for the daemon.
WORKDIR = "/"
# Default maximum for the number of available file descriptors.
MAXFD = 1024
# The standard I/O file descriptors are redirected to /dev/null by default.
if (hasattr(os, "devnull")):
   REDIRECT_TO = os.devnull
else:
   REDIRECT_TO = "/dev/null"
def goDaemon():
   try:
      pid = os.fork()
   except OSError, e:
      raise Exception, "%s [%d]" % (e.strerror, e.errno)
   if (pid == 0):       # The first child.
      os.setsid()
      try:
         pid = os.fork()        # Fork a second child.
      except OSError, e:
         raise Exception, "%s [%d]" % (e.strerror, e.errno)
      if (pid == 0):    # The second child.
         os.chdir(WORKDIR)
         os.umask(UMASK)
      else:
         os._exit(0)
   else:
      os._exit(0)       # Exit parent of the first child.
   import resource
   maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
   if (maxfd == resource.RLIM_INFINITY):
      maxfd = MAXFD
   for fd in range(0, maxfd):
      try:
         os.close(fd)
      except OSError:   # ERROR, fd wasn't open to begin with (ignored)
         pass
   os.open(REDIRECT_TO, os.O_RDWR)      # standard input (0)
   os.dup2(0, 1)                        # standard output (1)
   os.dup2(0, 2)                        # standard error (2)
   return(0)
###############End Module#######################

On Tue, Feb 26, 2008 at 12:06 PM, bharath venkatesh <bharathv6 at gmail.com>
wrote:

> hi ..
>        hi i want a program to start running as daemon in background .. my
> program is server listen to a client ... so i want to make that program run
> as daemon .. when i execute the program the program for ex server.py it
> should automatically start running as daemon in the background even if i
> close the terminal it shouldn't stop executing.. (right now if i close the
> terminal the process exits) can any one tell how to do it  in python as i
> have implemented the server  in python  ...
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
Regards--
Rishi Pathak
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080226/e6211702/attachment-0001.html>


More information about the Python-list mailing list