1. 程式人生 > >【Linux】GDB除錯多執行緒和多程序以及Core檔案

【Linux】GDB除錯多執行緒和多程序以及Core檔案

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