linux 线程id 进程id,在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<: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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值