gdb調試多進程多線程

1. 默認設置下,在調試多進程程序時GDB只會調試主進程。但是GDB(>V7.0)支持多進程的分別以及同時調試,換句話說,GDB可以同時調試多個程序。只需要設置follow-fork-mode(默認值:parent)和detach-on-fork(默認值:on)即可。
      follow-fork-mode  detach-on-fork   說明
parent                   on               只調試主進程(GDB默認)
child                     on               只調試子進程
parent                   off              同時調試兩個進程,gdb跟主進程,子進程block在fork位置
child                     off              同時調試兩個進程,gdb跟子進程,主進程block在fork位置
   設置方法:set follow-fork-mode [parent|child]   set detach-on-fork [on|off]

   查詢正在調試的進程:info inferiors
   切換調試的進程: inferior <infer number>
   添加新的調試進程: add-inferior [-copies n] [-exec executable] ,可以用file executable來分配給inferior可執行文件。

   其他:remove-inferiors infno, detach inferior


2. GDB默認支持調試多線程,跟主線程,子線程block在create thread。
   查詢線程:info threads
   切換調試線程:thread <thread number>


程序代碼:

#include <stdio.h>
#include <pthread.h>

void child()
{
	int i = 0;
	printf("child; %d\n", i);
}

void father()
{
	int i = 1;
	printf("father: %d\n", i);
}

void *thread_run(void *arg)
{

		int count = 0;
		while(count++ < 5)
		{
			sleep(1);
			printf("T am new thread,tid:%lu, pid:%d\n", pthread_self(), getpid());
		}
		pthread_exit((void *)123);
}

int main()
{
	pid_t pid = fork();
	if(pid == 0)
		child();
	else
		father();

	pthread_t id;
	pthread_create(&id, NULL, thread_run, NULL);
	while(1)
	{
		sleep(1);
		printf("I am main thread,tid:%lu, pid:%d\n", pthread_self(), getpid());
	}
	sleep(4);
	int ret2 = pthread_cancel(id);
	void *val = NULL;
	int ret = pthread_join(id, &val);
	printf("The new thread is quit.val:%d\n", (int)val);
	printf("%lu\n",id);
	return 0;
}

調試:

1. 調試主進程,block子進程。



2.切換到子進程



3.調試主進程中的子線程



4.切換線程


發佈了76 篇原創文章 · 獲贊 17 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章