Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kernel: how to find all threads from a process's task_struct?

Given a task struct for a process or a thread, what's the idiom of iterating through all other threads belonging to the same process?

like image 722
zer0stimulus Avatar asked Dec 09 '22 04:12

zer0stimulus


1 Answers

Linux does not distinguish between a process(task) and a thread. The library calls fork() and pthread_create() use the same system call clone(). The difference between fork() and pthread_create() is the bitmask passed to clone(). This bitmask describes which resources (memory, files, filesystems, signal handler,...). See man clone(2) for the details.

Anyway there is something called a thread group and a special flag to the clone() call which indicates that the new process belongs the the same thread group. This mechanism is normally used to keep together all tasks which are created with clone() specifying CLONE_THREAD in the bitmask. For this threads there exists the macro while_each_thread in the linux/sched/signal.h include file. It is used like this:

struct task_struct *me = current;
struct task_struct *t = me;
do {
    whatever(t);
} while_each_thread(me, t);
like image 187
bofh.at Avatar answered Mar 07 '23 21:03

bofh.at