应用程序段错误堆栈打印,嵌入到应用程序,打印同时记录到syslog,方便查看段错误原因
gcc -g -rdynamic -O0 strlen_test.c -o strlen_test
-
#include <stdio.h>
-
#include <string.h>
-
#include <unistd.h>
-
-
#include <signal.h>
-
#include <execinfo.h>
-
#include <syslog.h>
-
#include <stdlib.h>
-
-
#define SIZE 1024
-
static void *trap_buffer[SIZE];
-
static void fault_trap(int n, siginfo_t* msiginfo, void* myact)
-
{
-
int i, num;
-
char **calls;
-
-
printf("Fault address:%p\n", msiginfo->si_addr);
-
syslog(LOG_USER | LOG_ERR, "DROPSTAT:SIGSEGV-%p \n", msiginfo->si_addr);
-
num = backtrace(trap_buffer, SIZE);
-
calls = backtrace_symbols(trap_buffer, num);
-
for (i = 0; i < num; i++) {
-
printf("%s\n", calls[i]);
-
syslog(LOG_USER | LOG_ERR, "DROPSTAT:SIGSEGV-%s \n", calls[i]);
-
}
-
exit(1);
-
}
-
static void setup_trap()
-
{
-
struct sigaction act;
-
-
sigemptyset(&act.sa_mask);
-
act.sa_flags=SA_SIGINFO;
-
act.sa_sigaction=fault_trap;
-
sigaction(SIGSEGV,&act,NULL);
-
}
-
-
-
int main()
-
{
-
//char *p = 100 ;
-
char *p = NULL ;
-
unsigned long len = 0 ;
-
-
sleep(30);
-
-
setup_trap();
-
-
//len = strlen(p) ; //报错
-
*p = 5;
-
-
return 0;
-
}
===============
/ # ./strlen_test
Fault address:(nil)
./strlen_test() [0x400981]
/lib/libc.so.6() [0x3902833350]
./strlen_test(main+0x30) [0x400a7f]
/lib/libc.so.6(__libc_start_main+0xf1) [0x3902820531]
./strlen_test(_start+0x2a) [0x40085a]
/ #
sh-4.4# cat var/log/syslog | tail
2019-09-23T19:55:34.574950+00:00 (none) strlen_test: DROPSTAT:SIGSEGV-(nil)
2019-09-23T19:55:34.575243+00:00 (none) strlen_test: DROPSTAT:SIGSEGV-./strlen_test() [0x400981]
2019-09-23T19:55:34.575279+00:00 (none) strlen_test: DROPSTAT:SIGSEGV-/lib/libc.so.6() [0x3902833350]
2019-09-23T19:55:34.575306+00:00 (none) strlen_test: DROPSTAT:SIGSEGV-./strlen_test(main+0x30) [0x400a7f]
2019-09-23T19:55:34.575334+00:00 (none) strlen_test: DROPSTAT:SIGSEGV-/lib/libc.so.6(__libc_start_main+0xf1) [0x3902820531]
2019-09-23T19:55:34.575359+00:00 (none) strlen_test: DROPSTAT:SIGSEGV-./strlen_test(_start+0x2a) [0x40085a]
其他:
参数解释
If SA_SIGINFO is specified in sa_flags, then sa_sigaction (instead of sa_handler) specifies the signal-handling function for signum. This
function receives the signal number as its first argument, a pointer to a siginfo_t as its second argument and a pointer to a ucontext_t
(cast to void *) as its third argument. (Commonly, the handler function doesn't make any use of the third argument. See getcontext(3)
for further information about ucontext_t.)
阅读(1390) | 评论(0) | 转发(0) |