c++ - 如何从 pthread 获取 pid

标签 c++ linux pthreads

在 RH Linux 中,每个 pthread 都映射到一个 pid,可以在 htop 等工具中对其进行监控。但是我怎样才能得到一个线程的pid? getpid() 只返回主线程的 pid。

最佳答案

有两个线程值容易混淆。 pthread_self()将返回 POSIX 线程 ID; gettid()将返回操作系统线程 ID。后者是特定于 Linux 的,不能保证可移植,但可能是您真正需要的。

编辑 正如 PlasmaHH 指出的那样,gettid() 是通过 syscall() 调用的。来自 syscall() 手册页:

   #define _GNU_SOURCE
   #include <unistd.h>
   #include <sys/syscall.h>
   #include <sys/types.h>

   int
   main(int argc, char *argv[])
   {
       pid_t tid;

       tid = syscall(SYS_gettid);
   }

关于c++ - 如何从 pthread 获取 pid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7271154/

相关文章:

c - 使用 pthread 模拟循环

pthreads - 处理segfault信号SIGSEGV需要使用siginfo_t确定segfault的原因

c++ - 对 C++ 从函数返回引用的困惑

c++ - 使用 find 和 Union 检测 Graph 中的循环

c++ - gtkmm3 示例未编译(未定义引用)

python - 脚本通过 IDLE 运行时找到必要的文件,但通过终端运行时找不到该文件

linux - 18 06,12,18 * * * 这在 cron 发出时间中意味着什么?

c++ - 不能在指针数组中赋值

python - pypyodbc 在 isql 连接时不连接?

c - 指向 pthread_create() 最后一个参数的指针导致崩溃