如何在linux上没有gdb / pstack的情况下获取进程的所有线程pthread_t id

时间:2018-06-05 09:28:01

标签: multithreading

我想打印一个进程的所有线程堆栈,没有pstack,gdb。我想使用pthread_kill向所有线程发送自定义信号,并使用signal_handler接受它然后打印当前线程堆栈, 但问题是如何才能获得所有线程ID? 我已经尝试过了:在/ proc / $ pid / task下读取子目录,但是它代表LWP线程,而不是pthread_t。

1 个答案:

答案 0 :(得分:0)

// try to print all threads backtrace
if (DIR* dir = opendir("/proc/self/task")) {
  int thread_id;
  while (dirent* entry = readdir(dir)) {
    if (entry->d_name[0] == '.')
      continue;
    try {
      thread_id = std::stol(entry->d_name);
      ldout(m_cct, 1) << "send SIGUSR2 to " << thread_id << dendl;
      syscall(SYS_tgkill, getpid(), thread_id, SIGUSR2);
      t.sleep();
    } catch (const std::exception &e) {
      // pass
    }
  }
  closedir(dir);
}