Is it a Python bug that the main thread of a process created in a daemon thread is a daemon itself?
Question: When I call `os.fork()` inside a daemon thread, the main thread in the child
process has the `daemon` property set to `True`. This is very confusing, since
the program keeps running while the only thread is a daemon. According to the
docs, if all the threads are daemons the program should exit.

Here is an example:

    
    
    import os
    import threading
    
    
    def child():
         assert not threading.current_thread().daemon  # This shouldn't fail
    
    
    def parent():
        new_pid = os.fork()
        if new_pid == 0:
            child()
        else:
            os.waitpid(new_pid, 0)
    
    
    t = threading.Thread(target=parent)
    t.setDaemon(True)
    t.start()
    t.join()
    

Is it a bug in the CPython implementation?


Answer: The reason for this behaviour is that the daemonization is only relevant for
threads _other_ than the main-thread. In the main-thread, the return-value of
`current_thread().daemon` is hard-coded to be `False`.

See the relevant source code here:

<https://github.com/python/cpython/blob/2.7/Lib/threading.py#L1097>

So after a fork, there is only one thread, and it's consequently the main-
thread.

Which means it can never be a daemon-thread.

I can not point you to any documentation beyond the source, but it is most
certainly _not_ a bug - it would be a bug the other way round, if your
expectation was met.

The interaction between fork and threads are complex, and as I mentioned:
don't mix them before fork.

