linux下使用gdb调试崩溃和死锁实例

gdb是linux下一款功能强大的调试工具,windows下对应的有windbg,下面举例说明常见程序错误解决方法

1.gdb启动

要想使用gdb调试,编译时指定-g选项加入调试信息,gdb可以启动执行文件,attach正在运行程序,调试程序崩溃产生core文件

启动gdb后输入run运行,continue继续,quiet退出,下面是调试一段崩溃和死锁的源码

 

#include <pthread.h> 
#include <stdlib.h> 
#include <stdio.h> 
#include <unistd.h> 
#include <string.h> 

pthread_mutex_t mutex; 

int count = 0;
void print_pid_tid() 
{ 
	pid_t   pid; 
	pthread_t   tid; 

	pid = getpid(); 
	tid = pthread_self(); 

	printf("pid %u tid %u (0x%x)\n", (unsigned int)pid, 
		(unsigned int)tid, (unsigned int)tid); 
} 


void callback_func()
{
	pthread_mutex_lock(&mutex); 
	printf("count:%d\n",count);
}

void *thread_func1(void *arg) 
{ 
	while (1)
	{
		int n = *((int *)arg);
		pthread_mutex_lock(&mutex); 
		print_pid_tid(); 
		count += 2;
		for (int i=0 ; i < 5; ++i ) 
		{
			count += n;
		} 
		callback_func();
		pthread_mutex_unlock(&mutex); 
		sleep(1);
	}
	return 0;
} 
void *thread_func2(void *arg)
{
	while (1)
	{
		pthread_mutex_lock(&mutex); 
		printf("thread_func2 run\n");
		pthread_mutex_unlock(&mutex); 
		sleep(1);
	}
	return 0;
}
void *thread_func3(void *arg)
{
	while(1)
	{
		char *str = NULL;
		//strcpy(str,"hello world");
		sleep(1);
	}

	return 0;
}

int main(void) 
{ 
	pthread_t ntid; 
	int count = 10; 

	pthread_mutex_init(&mutex, NULL); 

	int err = pthread_create(&ntid, NULL, thread_func1, &count); 
	if ( 0 != err ) 
	{ 
		printf("pthread_create1:%s\n", strerror(err)); 
	} 
	err = pthread_create(&ntid, NULL, thread_func2, &count); 
	if ( 0 != err ) 
	{ 
		printf("pthread_create2:%s\n", strerror(err)); 
	}
	err = pthread_create(&ntid, NULL, thread_func3, &count); 
	if ( 0 != err ) 
	{ 
		printf("pthread_create3:%s\n", strerror(err)); 
	}
	getchar();

	int **ret = NULL; 
	pthread_join(ntid, (void**)ret); 
	printf("pthread_join:%p\n", *ret); 

	pthread_mutex_destroy(&mutex); 


	return 0; 
} 


2.调试崩溃

 

gdb绑定程序运行崩溃时,gdb会停留在程序最后运行栈位置,一般输入bt查看堆栈,frame n切换栈帧,print打印是否空指针导致崩溃,where查看对于源码位置或者list列出源代码,崩溃一般有空指针,数组越界,内存非法访问

3.调试死锁

程序出现死锁时会是卡死状态,如果gdb绑定运行使用ctrl+c中断程序,输入info threads查看所有线程,使用thread n切换线程,在线程中输入bt查看线程堆栈,定位程序停留位置,一般比较多个线程锁或者是否有死循环



4.断点调试

设置断点,如b main.cpp:31,执行到断点后next单步,step进入函数,continue继续运行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值