lvella
lvella

Reputation: 13491

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

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

Upvotes: 10

Views: 6783

Answers (1)

lvella
lvella

Reputation: 13491

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

Upvotes: 14

Related Questions