在Linux上显示正在运行的进程的线程ID

时间:2023-03-10 05:22:03
在Linux上显示正在运行的进程的线程ID

在Linux上显示正在运行的进程的线程ID

在上Linux,“ ps -T”可以显示正在运行的进程的线程信息:

# 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

proc伪文件系统上,有一个task目录来记录线程信息:

# 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

由于C++17,有一个文件系统库可用于访问文件系统,因此我利用该库遍历/proc/$pid/task文件夹以获取进程的线程ID:

    ......
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';
}
......

生成并运行它:

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

编程资料 https://www.cppentry.com