应用程序段错误堆栈打印,嵌入到应用程序,打印同时记录到syslog,方便查看段错误原因
gcc -g -rdynamic -O0 strlen_test.c -o strlen_test

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <unistd.h>

  4. #include <signal.h>
  5. #include <execinfo.h>
  6. #include <syslog.h>
  7. #include <stdlib.h>

  8. #define SIZE 1024
  9. static void *trap_buffer[SIZE];
  10. static void fault_trap(int n, siginfo_t* msiginfo, void* myact)
  11. {
  12.     int i, num;
  13.     char **calls;
  14.     
  15.     printf("Fault address:%p\n", msiginfo->si_addr);
  16.     syslog(LOG_USER | LOG_ERR, "DROPSTAT:SIGSEGV-%p \n", msiginfo->si_addr);
  17.     num = backtrace(trap_buffer, SIZE);
  18.     calls = backtrace_symbols(trap_buffer, num);
  19.     for (i = 0; i < num; i++) {
  20.             printf("%s\n", calls[i]);
  21.             syslog(LOG_USER | LOG_ERR, "DROPSTAT:SIGSEGV-%s \n", calls[i]);
  22.     }            
  23.     exit(1);
  24. }
  25. static void setup_trap()
  26. {
  27.     struct sigaction act;

  28.     sigemptyset(&act.sa_mask);
  29.     act.sa_flags=SA_SIGINFO;
  30.     act.sa_sigaction=fault_trap;
  31.     sigaction(SIGSEGV,&act,NULL);
  32. }


  33. int main()
  34. {
  35.     //char *p = 100 ;
  36.     char *p = NULL ;
  37.     unsigned long len = 0 ;
  38.     
  39.     sleep(30);
  40.     
  41.     setup_trap();
  42.     
  43.     //len = strlen(p) ; //报错
  44.     *p = 5;
  45.     
  46.     return 0;
  47. }
===============



/ # ./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.)



01-03 18:04