源程序是Linux下 cp命令的一个实现。
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#define PMODE 0644
int main(int argc, char *argv[]){
int fdin, fdout,n;
char buf[BUFSIZ];
if(argc!=3){
fprintf(stderr,"Usage: %s filein fileout\n", argv[0]);
exit(1);
}
if((fdin=open(argv[1],O_RDONLY))==-1){
perror(argv[1]);
exit(2);
}
if((fdout=open(argv[2],O_WRONLY|O_CREAT| O_TRUNC,PMODE))==-1){
perror(argv[2]);
exit(3);
}
while((n=read(fdin,buf,BUFSIZ))>0){
write(fdout,buf,n);
}
exit(0);
}
gcc -Wall -g -o cp.out cp.c
//注意 1: -Wall是打印警告信息,-g是增加调试信息,否则后面GDB无法据此进行调试,-o 是指定输出文件名
//2.如果用-c的话,会只生成编译后的目标文件.o,没有链接库,并不能直接执行。
GDB调试过程:
首先执行:
gdb cp.out
进入GDB后,设置程序的输入参数: ./test.c ./test.txt
//注意:这里设置参数的方式也可以以文件的方式,如 set args -i main.conf
[liuqiang@mu01 cp]$ gdb ./cp.out
GNU gdb (GDB) Red Hat Enterprise Linux (7.0.1-42.el5)
Copyright (C) 2009 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 "i386-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /home/liuqiang/commandTest/cp/cp.out...done.
(gdb) set args ./test.c ./test.txt
//然后使用start命令开始执行程序
(gdb) start
Temporary breakpoint 1 at 0x80484ce: file cp.c, line 11.
Starting program: /home/liuqiang/commandTest/cp/cp.out ./test.c ./test.txt
Temporary breakpoint 1, main (argc=3, argv=0xbfffe9a4) at cp.c:11
11 if(argc!=3){
(gdb) n
//使用n命令可以next step 逐步调试,s(step into) 可以进入函数,p可以打印变量值
16 if((fdin=open(argv[1],O_RDONLY))==-1){
(gdb) n
21 if((fdout=open(argv[2],O_WRONLY|O_CREAT| O_TRUNC,PMODE))==-1){
(gdb) p argv[0]
$1 = 0xbfffeacf "/home/liuqiang/commandTest/cp/cp.out"
(gdb) p argv[1]
$2 = 0xbfffeaf4 "./test.c"
(gdb) s
26 while((n=read(fdin,buf,BUFSIZ))>0){
(gdb) s
27 write(fdout,buf,n);
(gdb) n
26 while((n=read(fdin,buf,BUFSIZ))>0){
(gdb) n
30 exit(0);
(gdb) n
Program exited normally.
(gdb) quit //调试结束
断点调试:
(gdb) b cp.c:27
Breakpoint 1 at 0x80485a4: file cp.c, line 27.
(gdb) run
Starting program: /home/liuqiang/commandTest/cp/cp.out ./test.c ./test.txt
Breakpoint 1, main (argc=3, argv=0xbfffe9a4) at cp.c:27
27 write(fdout,buf,n);
(gdb) n
26 while((n=read(fdin,buf,BUFSIZ))>0){
(gdb)