Recently I've been learning about pthread. Then I suddenly came out of an idea that how does gdb know I create a new thread. Then I wrote down a test code below and started up gdb. I step into pthread_create() function, but instead of letting it return normally, I use return 0 to return pthread_create() function. But gdb still shows that I have only one thread. At first, I thought that gdb got thread information from the return value from the pthread_create() function then I thought gdb might also use child process info to the get thread info so I edited my test code. But the result wasn't what I thought of.
So how does gdb get thread info? What kind of information it needs to know how many threads the main thread have and which thread I'm on.
Code
#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;
}
}