c - 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;
}
}
解决方案
gdb如何检测pthread?
GDB 在 上设置内部断点_dl_debug_state
,这允许它跟踪加载了哪些共享库(这是调试共享库所必需的)。
当它观察到libpthread.so
已加载时,它会加载libthread_db.so.1
到自己的进程空间(加载到 GDB 本身,而不是加载到正在调试的程序中),并要求该库在新线程创建和销毁时通知 GDB。文档。
对的libthread_db
内部有深入的了解libpthread
,并安装了适当的钩子来实现此类通知。
推荐阅读
- c# - Linq:ForEach 项目返回从该项目开始获取 n 个唯一项目所需的项目数
- regex - 如何按照某种模式获取字符串?
- python - 如何在 Python 中将 base64 编码的字符串转换为没有磁盘 I/O 的文件(用于 HTTP 请求)
- javascript - Javascript 中的月/日比较
- java - Cucumber Runner Class 未运行 Step Definitons
- javascript - 仅在悬停时显示文本
- openmdao - 约束处理、整数和并行优化
- ruby - Chef Exec Rspec 错误:引发 ArgumentError(示例之外的错误)
- javascript - jQuery slideToggle 函数对我的输入框没有预期的效果
- javascript - 使用时刻 js 在 mongo db 中恢复日期和时间