標籤:data- class version 查看 turn png let gcc sas
原文: http://blog.csdn.net/feixiaoxing/article/details/7199643
用gdb調試多進程的程式會遇到困難,gdb只能跟蹤一個進程(預設是跟蹤父進程),而不能同時跟蹤多個進程,但可以設定gdb在fork之後跟蹤父進程還是子進程。以上面的程式為
#include <stdlib.h>#include <unistd.h>#include <stdio.h>#define MAXLINE 80int main(void){ int n; int fd[2]; pid_t pid; char line[MAXLINE]; if (pipe(fd) < 0) { perror("pipe"); exit(1); } if ((pid = fork()) < 0) { perror("fork"); exit(1); } if (pid > 0) /* parent */ { close(fd[0]); write(fd[1], "hello world\n", 12); wait(NULL); } else /* child */ { close(fd[1]); n = read(fd[0], line, MAXLINE); printf("---------------in-----------"); write(STDOUT_FILENO, line, n); } return 0;}
$ gcc main.c -g$ gdb a.outGNU gdb 6.8-debianCopyright (C) 2008 Free Software Foundation, Inc.License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>This is free software: you are free to change and redistribute it.There is NO WARRANTY, to the extent permitted by law. Type "show copying"and "show warranty" for details.This GDB was configured as "i486-linux-gnu"...(gdb) l2#include <unistd.h>3#include <stdio.h>4#include <stdlib.h>56int main(void)7{8pid_t pid;9char *message;10int n;11pid = fork();(gdb) 12if(pid<0) {13perror("fork failed");14exit(1);15}16if(pid==0) {17message = "This is the child\n";18n = 6;19} else {20message = "This is the parent\n";21n = 3;(gdb) b 17Breakpoint 1 at 0x8048481: file main.c, line 17.(gdb) set follow-fork-mode child(gdb) rStarting program: /home/akaedu/a.out This is the parent[Switching to process 30725]Breakpoint 1, main () at main.c:1717message = "This is the child\n";(gdb) This is the parentThis is the parent
---------------------------------------------------------------------
編寫代碼過程中少不了調試。在windows下面,我們有visual studio工具。在Linux下面呢,實際上除了gdb工具之外,你沒有別的選擇。那麼,怎麼用gdb進行調試呢?我們可以一步一步來試試看。
[cpp] view plain copy
- #include <stdio.h>
-
- int iterate(int value)
- {
- if(1 == value)
- return 1;
-
- return iterate(value - 1) + value;
- }
-
- int main()
- {
- printf("%d\n", iterate(10));
- return 1;
- }
既然需要調試,那麼產生的可執行檔就需要包含調試的資訊,這裡應該怎麼做呢?很簡單,輸入 gcc test.c -g -o test。輸入命令之後,如果沒有編譯和連結方面的錯誤,你就可以看到 可執行檔test了。
調試的步驟基本如下所示,
(01) 首先,輸入gdb test
(02) 進入到gdb的調試介面之後,輸入list,即可看到test.c源檔案
(03) 設定斷點,輸入 b main
(04) 啟動test程式,輸入run
(05) 程式在main開始的地方設定了斷點,所以程式在printf處斷住
(06) 這時候,可以單步跟蹤。s單步可以進入到函數,而n單步則越過函數
(07) 如果希望從斷點處繼續運行程式,輸入c
(08) 希望程式運行到函數結束,輸入finish
(09) 查看斷點資訊,輸入 info break
(10) 如果希望查看堆棧資訊,輸入bt
(11) 希望查看記憶體,輸入 x/64xh + 記憶體位址
(12) 刪除斷點,則輸入delete break + 斷點序號
(13) 希望查看函數局部變數的數值,可以輸入print + 變數名
(14)希望修改記憶體值,直接輸入 print + *地址 = 數值
(15) 希望即時列印變數的數值,可以輸入display + 變數名
(16) 查看函數的彙編代碼,輸入 disassemble + 函數名
(17) 退出調試輸入quit即可
linux下的C語言開發(gdb調試)