[2.4.2/Linux] Getting Python to fork?

Christian Heimes lists at cheimes.de
Mon Feb 4 16:31:32 CET 2008

Jon Ribbens wrote:
> Why? I don't think you do.
> Neither does BSD daemon.c or glibc daemon.c

The problem is well documented at

The second fork _is_ necessary, Jonathan Bartlett, 2003/10/31
The first fork accomplishes two things - allow the shell to return, and
allow you to do a setsid().

The setsid() removes yourself from your controlling terminal. You see,
before, you were still listed as a job of your previous process, and
therefore the user might accidentally send you a signal. setsid() gives
you a new session, and removes the existing controlling terminal.

The problem is, you are now a session leader. As a session leader, if
you open a file descriptor that is a terminal, it will become your
controlling terminal (oops!). Therefore, the second fork makes you NOT
be a session leader. Only session leaders can acquire a controlling
terminal, so you can open up any file you wish without worrying that it
will make you a controlling terminal.

So - first fork - allow shell to return, and permit you to call setsid()

Second fork - prevent you from accidentally reacquiring a controlling

More information about the Python-list mailing list