Creating a daemon process in Python

Nick Craig-Wood nick at craig-wood.com
Fri Feb 23 09:30:07 EST 2007


Eirikur Hallgrimsson <eh at mad.scientist.com> wrote:
>  def daemonize():
>      if (not os.fork()):
>          # get our own session and fixup std[in,out,err]
>          os.setsid()
>          sys.stdin.close()
>          sys.stdout = NullDevice()
>          sys.stderr = NullDevice()

That doesn't close the underlying file descriptors...

Here is another method which does :-

  null = os.open(os.devnull, os.O_RDWR)
  os.dup2(null, sys.stdin.fileno())
  os.dup2(null, sys.stdout.fileno())
  os.dup2(null, sys.stderr.fileno())
  os.close(null)


>          if (not os.fork()):
>              # hang around till adopted by init
>              ppid = os.getppid()
>              while (ppid != 1):
>                  time.sleep(0.5)
>                  ppid = os.getppid()

Why do you need hang around until adopted by init?  I've never see
that in a daemonize recipe before?

>          else:
>              # time for child to die
>              os._exit(0)
>      else:
>          # wait for child to die and then bail
>          os.wait()
>          sys.exit()

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list