Linux – How Threads Are Distinguished from Child Processes

linuxprocessthread

Linux doesn't actually distinguish between processes and threads, and implements both as a data structure task_struct.

So what does Linux provide to some programs for them to tell threads of a process from its child processes? For example, Is there a way to see details of all the threads that a process has in Linux?

Thanks.

Best Answer

From a task_struct perspective, a process’s threads have the same thread group leader (group_leader in task_struct), whereas child processes have a different thread group leader (each individual child process).

This information is exposed to user space via the /proc file system. You can trace parents and children by looking at the ppid field in /proc/${pid}/stat or .../status (this gives the parent pid); you can trace threads by looking at the tgid field in .../status (this gives the thread group id, which is also the group leader’s pid). A process’s threads are made visible in the /proc/${pid}/task directory: each thread gets its own subdirectory. (Every process has at least one thread.)

In practice, programs wishing to keep track of their own threads would rely on APIs provided by the threading library they’re using, instead of using OS-specific information. Typically on Unix-like systems that means using pthreads.