2011-03-11 72 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的情況下。