Skip to content
Advertisement

How does linux clean up threads when process exits if they’re really just processes under the hood?

My understanding is that threads and processes are really the same entity on Linux, the difference being in what memory is shared between them. I’m finding that it’s…difficult to ensure that child processes are properly cleaned up without explicit communication between the parent and child. I’d like to be able to run sub-processes with a similar mental model as threads, in that they’re cleaned up automatically when the parent exits, but with the memory safety that processes provide. How does Linux manage to clean up threads automatically, and can that same mechanism be used for child processes?

Advertisement

Answer

After reading the Linux source, I think I have the answer. Tasks are differentiated by their task ID and thread group ID. getpid() actually returns the thread group ID of the tasks, which is the same for all tasks in the group. This lets the kernel have a single notion of schedulable task which can be used to implement threading.

Since glibc 2.3, exit() actually invokes the exit_group syscall, rather than just the exit syscall. This syscall kills all the tasks in a thread group rather than just the calling task. It does this by sending a SIGKILL to all the tasks with the same thread ID.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement