- 论坛徽章:
- 0
|
附上demo的代码,这是backtrace.c
- #include <execinfo.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <signal.h>
- const char *SigInfo[][8] = {
- {
- "SIGSEGV: Address not mapped to object.",
- "SIGSEGV: Invalid permissions for mapped object.",
- },
- {
- "SIGFPE: Integer divide by zero.",
- "SIGFPE: Integer overflow.",
- "SIGFPE: Floating point divide by zero.",
- "SIGFPE: Floating point overflow.",
- "SIGFPE: Floating point underflow.",
- "SIGFPE: Floating point inexact result.",
- "SIGFPE: Floating point invalid operation.",
- "SIGFPE: Subscript out of range.",
- },
- };
- const char *GetSigCodeInfo(int signo, int code)
- {
- int sigIndex = 0, codeIndex = code - 1;
- if(signo == SIGSEGV)
- {
- sigIndex = 0;
- }
- else if(signo == SIGFPE)
- {
- sigIndex = 1;
- }
- else
- {
- return "Error signal info.";
- }
- return SigInfo[sigIndex][codeIndex];
- }
- void CatchSignalHandler(int n, siginfo_t *siginfo, void *myact)
- {
- void *array[100];
- int i = 0;
- int num = backtrace(array, sizeof(array)/sizeof(array[0]));
- char **calls = backtrace_symbols(array, num);
-
- printf("%s Fault address:%p\n", GetSigCodeInfo(siginfo->si_signo, siginfo->si_code), siginfo->si_addr);
- for (i = num - 1; i > 1; i--)
- {
- printf("%s\n", calls[i]);
- }
- exit(1);
- }
- void func(void)
- {
- int a, b, c = 0;
- a = b / c;
- }
- int main()
- {
- /* Init Signal Process */
- #if 1
- struct sigaction act;
- sigemptyset(&act.sa_mask);
- sigaddset(&act.sa_mask, SIGSEGV);
- sigaddset(&act.sa_mask, SIGFPE);
- act.sa_sigaction = CatchSignalHandler;
- act.sa_flags = SA_SIGINFO;
- sigaction(SIGSEGV, &act, NULL);
- sigaction(SIGFPE, &act, NULL);
- #endif
- func();
- return 0;
- }
复制代码 下面是fork_child.c
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <limits.h>
- #include <errno.h>
-
-
- int StartTask(const char *path)
- {
- int ret = 0;
-
- pid_t pid = vfork();
- if(pid == -1)
- {
- perror("vfork");
- ret = -1;
- }
- //start task
- else if(pid == 0)
- {
- execl(path, NULL);
- exit(0);
- }
- else
- {
- printf("start task %s, pid is %d\n", path, pid);
- }
-
- return ret;
- }
-
- int main(int argc, char **argv)
- {
- if(argc != 2){
- printf("%s child\n", argv[9]);
- return -1;
- }
- StartTask(argv[1]);
-
- sleep(1);
-
- return 0;
- }
复制代码
|
|