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

前端 未结 1 565
耶瑟儿~
耶瑟儿~ 2021-01-05 14:55

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条回答
  • 2021-01-05 15:36

    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 */
        }
    
    0 讨论(0)
提交回复
热议问题