栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在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 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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/232186.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号