I am an iOS developer and trying to get backtrace of the main thread when in a child thread.
First of all, anything like performSelector
or dispatch_async
doesn't work because it will destroy the current backtrace of main thread.
I am not good at C/C++ programming so look into the symbols in memory seems impossible to me.
In my opinion, the key to solve this problem is to get code executed in a particular thread without calling a method. This article inspires me to use signal.
I know that pthread_kill
can send a signal to a particular thread and then a handler can catch this signal. However I can't find and runnable demo about this. All demos I found use a handler to catch signal generated outside the process, e.g. press Ctrl + C
.
I tried the code below but still got a signal SIGINT
which means it is not caught by the handler.
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <pthread.h>
void sig_handler(int signum) {
printf("Received signal %d\n", signum);
}
int main() {
signal(SIGINT, sig_handler);
pthread_kill(pthread_self(), SIGINT);
return 0;
}
I've also heard that use printf
is not safe in a signal handler. So I wonder is it possible to use signal to get backtrace of other threads.