Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 804
lvella Avatar asked Apr 07 '15 21:04

lvella


People also ask

How do I see all threads in Linux?

To enable thread views in the top output, invoke top with "-H" option. This will list all Linux threads. You can also toggle on or off thread view mode while top is running, by pressing 'H' key.

How do I find the thread ID of a process in Linux?

Identifying the thread On Unix® and Linux® systems, you can use the top command: $ top -n 1 -H -p [pid]replacing [pid] with the process ID of the affected process. On Solaris®, you can use the prstat command: $ prstat -L -p [pid]replacing [pid] with the process ID of the affected process.

How can I tell how many threads a process has?

To get the total number of the threads(tiny pieces of a process running simultaneously) of a you can use the command ps -o nlwp <pid> It works all the time.


1 Answers

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 */
    }
like image 102
lvella Avatar answered Oct 08 '22 17:10

lvella