GDB調試器
基本概念
GDB是GNU開源組織發佈的一個強大的UNIX下的程序調試工具。或許,各位比較喜歡那種圖形界面方式的,像VC、BCB等IDE的調試,但如果你是在UNIX平臺下做軟件,你會發現GDB這個調試工具有比VC、BCB的圖形化調試器更強大的功能。所謂“寸有所長,尺有所短”就是這個道理。
主要功能
1、啓動程序,可以按照你的自定義的要求隨心所欲的運行程序。2、可讓被調試的程序在你所指定的調置的斷點處停住。(斷點可以是條件表達式)
3、當程序被停住時,可以檢查此時你的程序中所發生的事。
4、動態的改變你程序的執行環境。
GDB的基本指令
GDB調試多線程
代碼示例
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<sys/types.h>
void* thread1_run(void* arg)
{
printf("thread one is running~ ! pid : %d , tid : %u\n",getpid(), pthread_self());
pthread_exit((void*)1);
}
void* thread2_run(void* arg)
{
printf("thread two is running~ ! pid : %d , tid : %u\n",getpid(), pthread_self());
pthread_exit((void*)2);
}
int main()
{
pthread_t t1,t2;
pthread_create(&t1,NULL,&thread1_run,NULL);
pthread_create(&t2,NULL,&thread2_run,NULL);
void* ret1 = NULL;
void* ret2 = NULL;
pthread_join(t1,&ret1);
pthread_join(t2,&ret2);
printf("ret1 is :d\n",ret1);
printf("ret2 is :d\n",ret2);
return 0;
}
gdb進行調試
GDB調試多進程
在默認情況下是調試多進程程序時GDB會默認調試主進程,但是GDB支持多進程的分別與同步調試。即GDB支持同時調試多個進程,只需要設置follow-fork-mode(默認爲parent)和detach-on-fork(默認爲on)即可。我們還可以使用catch fork指令,如果fork異常,會停止程序。
設置方法: set follow-fork-mode[parent|child] set detach-on-fork[on|off]
顯示:show follow-fork-mode show detach-on-fork
測試代碼
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
int main()
{
printf("restart\n");
pid_t pid = fork();
if(pid == 0)
{
printf("child --> pid : %d , ppid : %d\n",getpid(),getppid());
sleep(1);
}
else
{
printf("father --> pid : %d , ppid : %d\n",getpid(),getppid());
sleep(1);
}
return 0;
}
只調試父進程
只調試子進程
同時進行調試(讓父進程運行調試,子進程阻塞等待)
core文件
基本概念
在一個程序崩潰時,它一般會在指定目錄下生成一個core文件。core文件僅僅是一個內存映象(同時加上調試信息),主要是用來調試的。
開啓或關閉core文件的生成
阻止系統生成core文件 ulimit -c 0
檢查生成core文件的選項是否打開 ulimit -a
查看機器參數 uname -a
查看默認參數 ulimit -a
設置core文件大小爲1024 ulimit -c 1024
設置core文件大小爲無限 ulimit -c unlimit
生成core文件,也可以是指定大小,然後使用gdb ./main core啓動,bt查看調用棧即可 ulimit -c unlimited
eg1(可以快速定位出問題的位置)
gdb a.out core.xxx
where
eg2 (在 gdb 中使用)
(gdb) core-file core.xxx
該命令將顯示所有的用戶定製,其中選項-a代表“all”。
也可以修改系統文件來調整core選項
在/etc/profile通常會有這樣一句話來禁止產生core文件,通常這種設置是合理的:
# No core files by default
ulimit -S -c 0 > /dev/null 2>&1
但是在開發過程中有時爲了調試問題,還是需要在特定的用戶環境下打開core文件產生的設置
在用戶的~/.bash_profile里加上ulimit -c unlimited來讓特定的用戶可以產生core文件
如果ulimit -c 0 則也是禁止產生core文件,而ulimit -c 1024則限制產生的core文件的大小不能超過1024kb