Last active
February 27, 2016 17:09
-
-
Save marcioj/15e8bd4b3a8495f2ebaf to your computer and use it in GitHub Desktop.
Print stacktraces in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// from http://stackoverflow.com/a/4732119/1846480 and adapted from a comment to not require sudo | |
// It's also needed to pass the -ggdb. For instance gcc source.c -o target.o -w -ggdb | |
#include <sys/prctl.h> | |
void print_trace() { | |
char pid_buf[30]; | |
sprintf(pid_buf, "%d", getpid()); | |
char name_buf[512]; | |
name_buf[readlink("/proc/self/exe", name_buf, 511)]=0; | |
prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0); | |
int child_pid = fork(); | |
if (!child_pid) { | |
dup2(2,1); // redirect output to stderr | |
fprintf(stdout,"stack trace for %s pid=%s\n",name_buf,pid_buf); | |
execlp("gdb", "gdb", "--batch", "-n", "-ex", "thread", "-ex", "bt", name_buf, pid_buf, NULL); | |
abort(); /* If gdb failed to start */ | |
} else { | |
waitpid(child_pid,NULL,0); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment