首页 > 解决方案 > gdb如何检测pthread?

问题描述

最近我一直在学习pthread。然后我突然冒出一个想法,gdb怎么知道我创建了一个新线程。然后我在下面写了一个测试代码并启动了gdb。我进入 pthread_create() 函数,但不是让它正常返回,而是使用return 0返回 pthread_create() 函数。但是 gdb 仍然显示我只有一个线程。起初,我认为 gdb 从 pthread_create() 函数的返回值中获取线程信息,然后我认为 gdb 也可能使用子进程信息来获取线程信息,所以我编辑了我的测试代码。但结果不是我想的那样。

那么 gdb 是如何获取线程信息的呢?它需要什么样的信息才能知道主线程有多少个线程以及我在哪个线程上。

代码

#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include "pthread.h"

void *foo(void *bar) {
        while(1) {
                printf("hello from thread: %d\n", pthread_self());
                sleep(2);
        }
}

int main() {
        printf("Before fake pthread_create");
        pid_t pid;
        if ((pid = fork()) == -1) {
                perror("fork error");
                exit(errno);
        }
        if (pid == 0) {
                while(1) {

                        sleep(3);
                }
        }

        if (pid > 0) {

                pthread_t thread;
                pthread_create(&thread, NULL, foo, NULL);
                while(1) {
                        printf("hello from thread: %d\n", pthread_self());
                        sleep(2);
                }
                return 0;
        }
}

标签: cgdbpthreads

解决方案


gdb如何检测pthread?

GDB 在 上设置内部断点_dl_debug_state,这允许它跟踪加载了哪些共享库(这是调试共享库所必需的)。

当它观察到libpthread.so已加载时,它会加载libthread_db.so.1自己的进程空间(加载到 GDB 本身,而不是加载到正在调试的程序中),并要求该库在新线程创建和销毁时通知 GDB。文档

对的libthread_db内部有深入的了解libpthread,并安装了适当的钩子来实现此类通知。


推荐阅读