- 论坛徽章:
- 0
|
附上相应的测试代码
#include <stdlib.h>
#include <signal.h>
#include <execinfo.h>
#include <stdio.h>
#include "testlib.h"
/* Obtain a backtrace and print it to stdout. */
void
print_trace (void)
{
void *array[10];
size_t size;
char **strings;
size_t i;
size = backtrace (array, 10);
strings = backtrace_symbols (array, size);
printf("\nthe calling stack is:\n-----------------%zd stack frames.--------------------\n",size);
for (i = 0; i < size; i++)
printf ("%s\n", strings[i]);
printf("------------------end of stack----------------------\n");
free (strings);
}
/* A dummy function to make the backtrace more interesting. */
void dummy_function (int sig)
{
if(sig==SIGSEGV)
printf("\n------------segmentation fault\n");
else if(sig==SIGBUS)
printf("\n------------bus error\n");
else if(sig==SIGTRAP)
printf("\n------------process is trapped\n");
print_trace ();
exit(1);
}
void fault()
{
int *p=0;
*p=1;
}
void func1()
{
fault();
}
void func2()
{
func1();
}
void func3()
{
func2();
}
void install_sigaction()
{
struct sigaction sact;
sigemptyset(&sact.sa_mask);
sact.sa_flags = 0;
sact.sa_handler = dummy_function;
sigaction(SIGTRAP, &sact, NULL);
sigaction(SIGSEGV, &sact, NULL);
sigaction(SIGBUS, &sact, NULL);
//dummy_function ();
func3();
}
int
main (void)
{
install_sigaction();
return 0;
} |
|