2011-03-11 21 views
0

继续上this problem后坏文件descriptor`,但我要重申:C:`写错误:叉,DUP2,和execv

对于一个家庭作业我写了一个基本的shell,包括重定向。该程序使用readline提示输入,解析输入字符串,并将其分解为可执行文件名称,参数和输入/输出文件(如果适用)。解析完字符串后,它将fork和子execv()传递给传入的可执行文件。我使用dup2()在fork之后和execv之前更改文件描述符,但是一旦遇到问题程序已经执行到新的可执行文件。如果在我的壳我跑ls > foo.out,我得到:ls: write error: Bad file descriptor

这里是我的子进程的代码(这是后叉()):

int _child(struct command *c){ 
    int ret; 
    /* When given `ls > foo.out`, these next two lines output: 
    ** c->infile is (null) 
    ** c->outfile is foo.out 
    */ 
    printf("c->infile is %s\n",c->infile); 
    printf("c->outfile is %s\n",c->outfile); 
    if(c->infile){ 
     int fd = open(c->infile, O_RDONLY); 
     int _fd_dup = dup2(fd,0); 
     close(0); 
     if(_fd_dup != 0){ 
      fprintf(stderr, "Failed to redirect command input.\n"); 
      return 0; 
     } 
    } 
    if(c->outfile){ 
     int fd = open(c->outfile, O_WRONLY | O_CREAT | O_TRUNC, 0600); 
     int _fd_dup = dup2(fd,1); 
     close(1); 
     if(_fd_dup != 1){ 
      fprintf(stderr, "Failed to redirect command output.\n"); 
      return 0; 
     } 
    } 

我没有得到“无法重定向命令输出“。错误。正如我所提到的,这是一项家庭作业,所以我不想找人解决这个问题,而是指向正确的方向。

回答

2

的问题是在此位的代码:

int _fd_dup = dup2(fd,1); 
    close(1); 

你应该关闭fd,不1。你也有同样的问题在fd 0的情况下。