简体   繁体   English

如何打印Linux上进程拥有的所有线程的线程ID

[英]How to print thread id of all threads a process on linux has

I know how to print thread id while executing in the context of a thread, but I would like to print all thread ids that a process has spawned.我知道如何在线程上下文中执行时打印线程 id,但我想打印进程产生的所有线程 id。 I need this to correlate with strace output for debugging.我需要将其与 strace 输出关联以进行调试。

How to get current thread id:如何获取当前线程ID:
pid_t x = syscall(__NR_gettid); pid_t x = 系统调用(__NR_gettid);

From https://unix.stackexchange.com/a/901/134332来自https://unix.stackexchange.com/a/901/134332

For each process, a lot of information is available in /proc/12345 where 12345 is the process ID.对于每个进程, /proc/12345中都有很多信息可用,其中12345是进程 ID。 Information on each thread is available in /proc/12345/task/67890 where 67890 is the kernel thread ID. /proc/12345/task/67890中提供了每个线程的信息,其中67890是内核线程 ID。 This is where ps, top and other tools get their information.这是 ps、top 和其他工具获取信息的地方。

You can read the virtual /proc filesystem.您可以读取虚拟/proc文件系统。 Iterate over the dirnames in /proc/self/task .遍历/proc/self/task中的目录名。

if(DIR* dir = opendir("/proc/self/task")) {
    while (dirent* entry = readdir(dir))
        if (entry->d_name[0] != '.')
            std::cout << entry->d_name;
    closedir(dir);
}

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

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