GCC和GDB调试linux下的cp命令实现

源程序是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) 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值