3

I am using pythons multiprocessing library to create some subprocesses. I implemented a way to terminate my child-processes gracefully.
To terminate them even if my main-process has a crash, I made all child-processes daemons as well.

My question is now: Who is responsible for terminating daemons, if the main process had a very hard crash or is killed immediately? Is the python-interpreter killing the child-processes or is the OS killing them as soon as the main-process is dead?

From the python documentation, I got

When a process exits, it attempts to terminate all of its daemonic child processes.

But for me that sounds like it is not guaranteed.

Does anybody know what the exact behaviour is?
I am working on Windows, but if Linux behaves different, it would also be interesting.

1 Answer 1

2

It is not spelled out, but it will call Process.terminate() on the child process. See the code base here.

The behaviour of terminate() differs between Windows and POSIX (eg. Linux) systems. On Windows it will call TerminateProcess(), which unconditionally forces a process to terminate. The full behaviour is described here. On POSIX systems, the process is sent the SIGTERM signal. This is a strong signal for the process to exit, but weaker than SIGKILL. SIGTERM asks the process to exit, whereas SIGKILL is more akin to the TerminateProcess() of Windows. The default behaviour on receiving a SIGTERM is to exit the process. However, a process may alter its signal handler to avoid terminating when it receives the SIGTERM signal. With SIGKILL, the process never receives the signal, the OS just stops scheduling any of the processes threads and starts cleanup.

The rationale for SIGTERM is that the parent process has no idea what the child process is doing. It could be in an integral bit of code, that if interrupted could lead to data corruption or other inconsistent states (eg. a database in the middle of committing a transaction). If your child process does not override its handler for SIGTERM then it will exit when it receives a SIGTERM. If you override the default handler using the signal module, then it is up to you make sure the process exits when it receives a SIGTERM.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.