简体   繁体   English

以编程方式获取与htop的相应pid匹配的进程的线程ID

[英]Get thread Id for a process programmatically that matches htop's corresponding pid

I have seen that in htop's tree mode my multithreaded program has several processes under it. 我已经看到,在htop的树模式下,我的多线程程序具有多个进程。 I know they are thread ids. 我知道它们是线程ID。 But this id doesn't match the thread id that was returned by the pthread_create function. 但是,此ID与pthread_create函数返回的线程ID不匹配。

int _id = pthread_create(&m_iAudioThreadID, NULL, AudioRecvThread, this);

Is the m_iAudioThreadID supposed to be equal to the PID we see in htop's tree mode for a process? m_iAudioThreadID是否应该等于我们在htop树状模式中看到的PID? It doesn't though. 虽然没有。 How do I find the PID of htop's programmatically from my program? 如何从程序中以编程方式找到htop的PID? Thanks. 谢谢。

Is the m_iAudioThreadID supposed to be equal to the PID we see in htop's tree mode for a process? m_iAudioThreadID是否应该等于我们在htop树状模式中看到的PID?

No, they are not. 不,他们不是。 htop shows you process-ids, PIDs. htop向您显示进程ID,PID。 PThread-IDs as set by pthread_create() are different: Distinction between processes and threads in Linux pthread_create()设置的PThread-ID不同: Linux中进程与线程之间的区别

One main difference is that PIDs are uniquely indentifying a process within the existing processes of a system, PThread-IDs are uniquely indentifying a thread within the existing threads of a process. 一个主要区别是PID在系统的现有进程中唯一地标识一个进程,PThread-ID在进程的现有线程中唯一地标识一个线程。

How do I find the PID of htop's programmatically from my program? 如何从程序中以编程方式找到htop的PID?

At least on a recent Linux: To get the PID associated to a certain PThread use the gettid() system call from within the thread in question: 至少在最近的Linux上:要获取与某个PThread关联的PID,请从相关线程内使用gettid()系统调用:

#define _GNU_SOURCE

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

pid_t gettid(void)
{
  return syscall(SYS_gettid);
}

(inspired by http://man7.org/linux/man-pages/man2/syscall.2.html ) (灵感来自http://man7.org/linux/man-pages/man2/syscall.2.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM