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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

小朋友学开发   2020-03-01 我要评论

在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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们