在Linux上的C语言中,如何获取进程的所有线程?
问题描述:
如何遍历当前进程所有线程的所有消息?有什么方法不涉及进入/proc
吗?
How to iterate through all tids of all threads of the current process? Is there some way that doesn't involve diving into /proc
?
答
基于阅读/proc
#include <sys/types.h>
#include <dirent.h>
#include <stdlib.h>
#include <stdio.h>
然后,从功能内部:
DIR *proc_dir;
{
char dirname[100];
snprintf(dirname, sizeof dirname, "/proc/%d/task", getpid());
proc_dir = opendir(dirname);
}
if (proc_dir)
{
/* /proc available, iterate through tasks... */
struct dirent *entry;
while ((entry = readdir(proc_dir)) != NULL)
{
if(entry->d_name[0] == '.')
continue;
int tid = atoi(entry->d_name);
/* ... (do stuff with tid) ... */
}
closedir(proc_dir);
}
else
{
/* /proc not available, act accordingly */
}