在Linux上,在C中,我如何获得进程的所有线程?

lve*_*lla 5 c linux system-calls

如何遍历当前进程的所有线程的所有tid?有什么方法不涉及潜入/proc

lve*_*lla 7

我正在使用的代码,基于阅读 /proc

#include <sys/types.h>
#include <dirent.h>
#include <stdlib.h>
#include <stdio.h>
Run Code Online (Sandbox Code Playgroud)

然后,从一个功能内部:

    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 */
    }
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考,`snprintf(dirname,sizeof dirname,"/ proc /%d/task",getpid());`可以替换为`"/ proc/self/task"`用于当前进程 (4认同)