Making a non-root daemon process

Leo Kislov Leo.Kislov at
Fri Mar 23 10:16:05 CET 2007

On Mar 22, 11:19 pm, Ben Finney <b... at> wrote:
> Howdy all,
> For making a Python program calve off an independent daemon process of
> itself, I found Carl J. Schroeder's recipe in the ASPN Python Cookbook.
> <URL:>
> This is a thorough approach, and I'm cribbing a simpler process from
> this example. One thing that strikes me is that the algorithm seems to
> depend on running the program as the root user.
>     import os
>     def become_daemon():
>         pid = os.fork()
>         if pid == 0:
>             # This is the child of the fork
>             # Become a process leader of a new process group
>             os.setsid()
>             # Fork again and exit this parent
>             pid = os.fork()
>             if pid == 0:
>                 # This is the child of the second fork -- the running process.
>                 pass
>             else:
>                 # This is the parent of the second fork
>                 # Exit to prevent zombie process
>                 os._exit(0)
>         else:
>             # This is the parent of the fork
>             os._exit(0)
>     become_daemon()
>     # Continue with the program
> The double-fork seems to be to:
>   - Allow the first forked child to start a new process group
>   - Allow the second forked child to be orphaned immediately
> The problem I'm having is that 'os.setsid()' fails with 'OSError:
> [Errno 1] Operation not permitted' unless I run the program as the
> root user. This isn't a program that I want necessarily running as
> root.

It works for me. I mean your program above produces no exceptions for
me on Debian 3.1 python2.4

> What does the 'os.setsid()' gain me?

It dettaches you from terminal. It means you won't receive signals
from terminal for sure. Like SIGINT and SIGHUP, but there are maybe

> How can I get that without being
> the root user?

Maybe you can go over the list of all possible signals from the
terminal and notify kernel that you want to ignore them. Sounds
similar to dettaching from the terminal, but maybe there some
differences. But the fact that os.setsid fails for you is weird

  -- Leo.

More information about the Python-list mailing list