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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值