linux下使用gdb调试崩溃和死锁实例
生活随笔
收集整理的這篇文章主要介紹了
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繼續運行
總結
以上是生活随笔為你收集整理的linux下使用gdb调试崩溃和死锁实例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 解决ubuntu apt-get ins
- 下一篇: SSD+HDD双硬盘+MSI主板win8