Making a non-root daemon process

Ben Finney ben at benfinney.id.au
Fri Mar 23 02:19:25 EDT 2007


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:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731>

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.

What does the 'os.setsid()' gain me? How can I get that without being
the root user?

-- 
 \       "I went to a general store. They wouldn't let me buy anything |
  `\                                  specifically."  -- Steven Wright |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list