Display running process’s thread IDs on Linux

On Linux, “ps -T” can show threads information of running process:

# ps -T 2739
  PID  SPID TTY      STAT   TIME COMMAND
 2739  2739 pts/0    Sl     0:00 ./spawn_threads
 2739  2740 pts/0    Sl     0:00 ./spawn_threads
 2739  2741 pts/0    Sl     0:00 ./spawn_threads

On proc pseudo file system, there is a task directory which records thread information:

# ls -lt /proc/2739/task
total 0
dr-xr-xr-x 7 root root 0 Jun 28 14:55 2739
dr-xr-xr-x 7 root root 0 Jun 28 14:55 2740
dr-xr-xr-x 7 root root 0 Jun 28 14:55 2741

Since C++17, there is a filesystem library which can be used to access file system, and I leverage this library to traverse the /proc/$pid/task folder to get the thread IDs of process:

    ......
    std::filesystem::path p{"/proc"};
    p /= argv[1];
    p /= "task";
    ......
    uint64_t thread_num{};
    std::vector<std::string> thread_id;

    std::filesystem::directory_iterator d_it(p);
    for (const auto& it : d_it)
    {
        thread_num++;
        thread_id.push_back(it.path().filename().string());
    }

    std::cout << "Process ID (" << argv[1] << ") has " << thread_num << " threads, and ids are:\n";
    for (const auto& v : thread_id)
    {
        std::cout << v << '\n';
    }
    ......

Build and run it:

# ./show_thread_ids 2739
Process ID (2739) has 3 threads, and ids are:
2739
2740
2741

P.S., the full code is here.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.