列出当前进程中的所有线程?

问题描述:

我试图执行一个系统调用,让我得到的线程数当前进程。我是新来的Linux内核,所以我对它的理解是有限的。

I'm trying to implement a syscall which allows me to get the number of threads for the current process. I am new to the linux kernel, and so my understanding of it is limited.

目前,我正尝试通过所有的task_structs迭代,他们的线程组领导的PID比作电流线程组领导的PID:

Currently, I am trying to iterate through all the task_structs, and compare their threadgroup leader's pid to the current threadgroup leader's pid:

// ...
int nthreads = 0;
struct task_struct *task_it;
for_each_process(task_it) {
    if (task_it->group_leader->pid == current->group_leader->pid) {
        nthreads++;
    }
}
// ...

不过,这似乎并不奏效(快速测试一些产卵的pthreads仍给 1 有关group_leader什么是共同在同一的所有线程流程?

However, this doesn't seem to be working (a quick test spawning some pthreads is still giving 1. What about the group_leader is common to all threads in the same process?

与code的问题是什么内核调用PID(即 PID 字段的的task_struct )是用户空间调用TID(即它是什么由 sys_gettid返回(),是每个线程唯一)。什么用户空间调用PID被称为TGID在内核(即工作组ID) - 这是什么 sys_getpid()系统调用返回

The problem with your code is that what the kernel calls a PID (the pid field of task_struct) is what userspace calls a TID (ie. it's what's returned by sys_gettid() and is unique per thread). What userspace calls a PID is called a TGID in the kernel (for "task group ID") - that's what the sys_getpid() syscall returns.

您不必实际检查TGID,虽然 - 只是比较结构的task_struct * 指针就足够了:

You don't need to actually check the TGID, though - just comparing the struct task_struct * pointers is enough:

if (task_it->group_leader == current->group_leader) {

顺便说一句,你可以只遍历了 thread_group 名单电流是的成员(含 while_each_thread()),那么你就不需要任何测试的。甚至更好,只需要使用 get_nr_threads(电流)

By the way, you could just iterate over the thread_group list that current is a member of (with while_each_thread()), then you wouldn't need any test at all. Or even better, just use get_nr_threads(current).

注意,遍历所有的任务列表需要被包裹在所有方法rcu_read_lock(); / rcu_read_unlock(); 是正确的。

Note that all methods that loop over the task lists need to be wrapped in rcu_read_lock(); / rcu_read_unlock(); to be correct.