yum install gdb Downloading Packages: gdb-7.2-90.el6.i686.rpm | 2.3 MB 02:25 Running Transaction Test Transaction Test Succeeded Installed: gdb.i686 0:7.2-90.el6 Complete!
編譯時務必帶 -g,否則 GDB 只會給你一堆記憶體位址,看不到函式名與變數名。
cc -g 0.c -o 0 gdb 0 (gdb) break 3 (gdb) break fun (gdb) r # 執行 (gdb) n # 單步(不進入函式) (gdb) c # 繼續 (gdb) p i # 印出變數 (gdb) printf i (gdb) bt # 查看函式呼叫堆疊 (gdb) finish # 跳出當前函式 (gdb) q # 離開
被追蹤的程式碼大致如下:
fun() {
int i=0;
for(; i<10; i++) {
printf("i = %d \n", i);
}
}
int main() {
fun();
return 0;
}
預設情況下,GDB 在 fork 之後會甩開子行程,這對除錯多線程程式是致命的。編譯時記得連結 pthread:
g++ -o m *.cpp *.h -lpthread
接著在 GDB 裡關掉自動 detach,並設一個 fork 捕捉點:
(gdb) set detach-on-fork off (gdb) show detach-on-fork Whether gdb will detach the child of a fork is off. (gdb) catch fork Catchpoint 1 (fork) (gdb) r Starting program: /home/sts/Desktop/20160728/m [Thread debugging using libthread_db enabled] [New Thread 0xb7feeb70 (LWP 11752)] put:2 [New Thread 0xb75edb70 (LWP 11753)] put:3 [New Thread 0xb6becb70 (LWP 11754)] get:2 [New Thread 0xb61ebb70 (LWP 11755)] get:0 put:5 put:7 get:0 ...
程式中斷後,用 info inferiors 查看有哪些行程,再用 inferior 切換:
(gdb) cont Continuing. ^C Program received signal SIGINT, Interrupt. 0x00110424 in __kernel_vsyscall () (gdb) info inferiors Num Description Executable * 1 process 11787 /home/sts/Desktop/20160728/m (gdb) inferior 1 [Switching to inferior 1 [process 11787]] [Switching to thread 1 (Thread 0xb7ff06d0 (LWP 11787))] #0 0x00110424 in __kernel_vsyscall ()
#include <stdio.h>
#include <pthread.h>
#include <iostream>
#include <unistd.h>
using namespace std;
/* 同步關係:多生產、多消費,位置共用 */
int ss[10];
int i=1;
int j=1;
void *s(void) {
while(i++) {
ss[i]=i;
cout << "put:" << ss[i] << endl;
sleep(2);
i = i%10+1;
}
}
void *x(void) {
while(j++) {
cout << "get:" << ss[j] << endl;
j = j%10+1;
sleep(2);
}
}
int main(void) {
pthread_t ids1, ids2, idx1, idx2;
pthread_create(&ids1, NULL, (void* (*)(void*))s, NULL);
pthread_create(&ids2, NULL, (void* (*)(void*))s, NULL);
pthread_create(&idx1, NULL, (void* (*)(void*))x, NULL);
pthread_create(&idx2, NULL, (void* (*)(void*))x, NULL);
pthread_join(ids1, NULL);
pthread_join(ids2, NULL);
pthread_join(idx1, NULL);
pthread_join(idx2, NULL);
return (0);
}
/* g++ -o m *.cpp *.h -lpthread */
這個範例刻意不加鎖,讓生產者與消費者共用同一個陣列位置,正好可以用來觀察 GDB 在多線程情境下的行為,也順便理解為什麼同步機制不可省略。
https://blog.csdn.net/pbymw8iwm/article/details/7876797