On Linux, in C, how can I get all threads of a process?

这一生的挚爱 提交于 2019-11-30 17:10:14

问题


How to iterate through all tids of all threads of the current process? Is there some way that doesn't involve diving into /proc?


回答1:


The code I am using, based on reading /proc

#include <sys/types.h>
#include <dirent.h>
#include <stdlib.h>
#include <stdio.h>

Then, from inside a funcion:

    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 */
    }


来源:https://stackoverflow.com/questions/29501309/on-linux-in-c-how-can-i-get-all-threads-of-a-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!