1. 程式人生 > >linux中的segment fault(也適應於嵌入式linux環境)

linux中的segment fault(也適應於嵌入式linux環境)

先上程式碼 t.c:

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>

static void _sig_usr(int signo)
{
    char buf[1024];
    char cmd[1024];
    FILE* fh;

    snprintf(buf, sizeof(buf), "/proc/%d/cmdline", getpid());
    if(!(fh = fopen(buf, "r")))
    {
        exit(0);
    }
    if(!fgets(buf, sizeof(buf), fh))
    {
        exit(0);
    }
    fclose(fh);
    
    if(buf[strlen(buf) - 1] == '\n')
    {
        buf[strlen(buf) - 1] = '\0';
    }
    snprintf(cmd, sizeof(cmd), "gdb %s %d", buf, getpid());
    system(cmd);

    exit(0);
}

static void _err_test_func(void)
{
    unsigned char* ptr = 0x00;
    *ptr = 0x00;
}

int main(int argc, char* argv[])
{

    signal(SIGSEGV, &_sig_usr); /*install signal for segment fault*/
    _err_test_func ();

    return 0;
}


編譯命令:

gcc -g -rdynamic t.c -o test.elf

執行過程:

-bash-3.00$./test.elf
GNU gdb Red Hat Linux (6.3.0.0-1.153.el4rh)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "i386-redhat-linux-gnu"...Using host libthread_db library "/lib/tls/libthread_db.so.1".

Attaching to program: /home/deeve/test.elf, process 19766
Reading symbols from /lib/tls/libc.so.6...done.
Loaded symbols for /lib/tls/libc.so.6
Reading symbols from /lib/ld-linux.so.2...done.
Loaded symbols for /lib/ld-linux.so.2
0x003fa7a2 in _dl_sysinfo_int80 () from /lib/ld-linux.so.2
(gdb)

bt
#0 0x003fa7a2 in _dl_sysinfo_int80 () from /lib/ld-linux.so.2
#1 0x004a3d23 in __waitpid_nocancel () from /lib/tls/libc.so.6
#2 0x0044d7a9 in do_system () from /lib/tls/libc.so.6
#3 0x08048820 in _sig_usr (signo=11) at t.c:28
#4 <signal handler called>
#5 0x0804883c in _err_test_func () at t.c:36
#6 0x08048876 in main (argc=1, argv=0xbfef87d4) at t.c:43
(gdb)
q
The program is running. Quit anyway (and detach it)? (y or n) y
Detaching from program: /home/deeve/test.elf, process 19766
-bash-3.00$


由以上執行過程可知,可以直接定位到出錯的函式/語句,其中(gdb)提示符後面的btq 需要自己手動輸入哦。

前提: 需要當前執行環境存在gdb,如果是嵌入式環境,需要你手動編譯一個在平臺可以使用的gdb,並新增到PATH中去。

原文地址: http://www.yuanma.org/data/2008/0818/article_3139.htm