我正在尝试实现一个syscall,它允许我获取当前进程的线程数。我是Linux内核的新手,所以我对它的理解有限。
目前,我正在尝试遍历所有的task_struct
,并将它们的线程组领导者的PID与当前线程组领导者的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++;
}
}
// ...
然而,这似乎不起作用(快速测试产生一些pthread仍然给出了1
。对于同一进程中的所有线程来说,group_leader
是通用的吗?
发布于 2012-10-23 14:34:54
您的代码的问题在于,内核所称的PID (task_struct
的pid
字段)就是用户空间所称的TID (即。它是由sys_gettid()
返回的,每个线程都是唯一的)。用户空间所称的PID在内核中称为TGID (表示“任务组ID") --这是sys_getpid()
系统调用返回的内容。
你不需要实际检查TGID --只需要比较struct task_struct *
指针就足够了:
if (task_it->group_leader == current->group_leader) {
顺便说一句,您可以只迭代current
所属的thread_group
列表(使用while_each_thread()
),那么您根本不需要任何测试。或者更好的是,直接使用get_nr_threads(current)
。
请注意,循环遍历任务列表的所有方法都需要包装在rcu_read_lock();
/ rcu_read_unlock();
中才能正确。
发布于 2012-10-22 05:42:22
这段代码是一个很好的演示。
下面的C程序在一个节点的进程表中创建一个所有进程的列表,并在一列中显示任何单个进程的线程数。使用此工具,可以确定网络守护进程在任何时候发生网络问题时都会创建一个新线程。严重的网络问题是导致登录问题的原因。
#include "sys/param.h"
#include "sys/pstat.h"
int main ( void )
{
struct pst_status * psa = NULL;
struct pst_status * prc = NULL;
struct pst_dynamic psd;
long nproc = 0;
long thsum = 0;
long i;
if ( pstat_getdynamic(&psd, sizeof(psd), 1, 0) == -1 )
(void)perror("pstat_getdynamic failed");
// Get the number of active processes from pst_dynamic
nproc = psd.psd_activeprocs;
psa = (struct pst_status *)malloc(nproc * sizeof(struct pst_status));
// Read the info about the active processes into the array 'psa'
if ( pstat_getproc(psa, sizeof(struct pst_status), nproc, 0) == -1 )
(void)perror("pstat_getproc failed");
(void)printf("\n\n------------------------------------------------------------------------------");
(void)printf("\n %5s | %5s |%7s| %5s | %s", "PID", "UID", "Threads", "RSS", "Command");
(void)printf("\n------------------------------------------------------------------------------");
// Report the process info as required
prc = (struct pst_status *)psa;
for (i=0; i < nproc; i++)
{
(void)printf("\n %5ld | ", prc->pst_pid);
(void)printf("%5ld | ", prc->pst_uid);
(void)printf("%5ld | ", prc->pst_nlwps);
(void)printf("%5ld | ", prc->pst_rssize);
(void)printf("%s ", prc->pst_cmd);
thsum += prc->pst_nlwps;
++prc;
}
(void)printf("\n\n*** %ld processes, %ld threads running\n\n", nproc, thsum);
(void)free(psa);
(void)exit(0);
}
这是另一个使用task_struct的链接:http://tuxthink.blogspot.com/2011/03/using-foreachprocess-in-proc-entry.html
https://stackoverflow.com/questions/13002444
复制相似问题