2012-04-07 64 views
0

我正在寫一個殼,我似乎在某個時候被關閉標準輸入,但我想不通的地方。我傾倒了這個代碼,但無法找到我可能關閉它的位置。C編寫外殼,關閉標準輸入某處

它只有當我使用像這樣的配管被封閉:

cat f2.txt | cat 

cat < f2.txt | cat 

cat | cat | cat 

其中該代碼被處理的線是232通過268然後通過270 288

我似乎無法得到正確的格式因此,這裏是格式化代碼:http://pastebin.com/pe8BkVPV

我也將粘貼在下面討論的部分。

任何想法?

if (ct->recieve_input == 1 && ct->redirect_output == 0) { 

ptr = dll_prev(tmp) ; 
    ctmp = jval_v(ptr->val) ; 
//fprintf(stderr, "Previous->command = %s\n", ctmp->command) ; 
fflush(stdout) ; 
      fs = fork() ; 
      if (fs == 0) { 

       if (ct->tdw == 1) { /* If we are redirecting output */ 
        fprintf(stderr, "ct->tdw = 1\n") ; 
        if (dup2(ct->fd1, 1) != 1) { perror("dup2 tdw A") ; exit(1) ; } 
        if (close(ct->fd1) < 0) { perror("c1"); exit(1); } 
       } /* tdw == 1 */ 

       if (ct->tdr == 1) { /* If we are recieving input */ 
        fprintf(stderr, "ct->tdr = 1\n") ; 
        if (dup2(ct->fd0, 0) != 0) { perror("dup2 tdr A") ; exit(1) ; } 
        if (close(ct->fd0) < 0) { perror("c0"); exit(1); } 
       } 

       if (dup2(ctmp->pipefd[0], 0) != 0) { 
        perror("dup2 : 0, 0") ; 
        exit(1) ; 
       } 
       //close(ct->pipefd[1]) ; 
       //close(ct->pipefd[0]) ; 
       close(ctmp->pipefd[1]) ; 
       close(ct->pipefd[1]) ; 



       status = execvp(ct->command, ct->args) ; 
       fprintf(stderr, "execvp command failed\n") ; 
       exit(1) ; 
      } 
     } 


     if (ct->redirect_output == 1 && ct->recieve_input == 0) { 
      ptr = (to_exec)->blink ; 
      ctmp = jval_v(ptr->val) ; 

      ctmp->recieve_input = 1 ; 
      fflush(stdout) ; 
      fs = fork() ; 

      if (fs == 0) { 

       if (dup2(ct->pipefd[1], 1) == -1) { 
        perror("dup2 : RD== 1:1, 1") ; 
        exit(1) ; 
       } 

       //close(ct->pipefd[0]) ; // TODO 
       status = execvp(ct->command, ct->args) ; 
       fprintf(stderr, "exevp command failed\n") ; 
       exit(1) ; 
      } 
     } /* End redirect output */ 
+0

管道結束時關閉的stdin。 此時,fgetchar()應該返回-1。 – LawfulHacker 2012-04-07 19:06:39

回答

0

至於我可以告訴你錯過了什麼是另一個

if (cc > 0) c->recieve_input = 1 ; 

行處理循環結束後。你需要練習你的DRY紀律(不要重複自己)。

P.S.你拼錯接收

+0

謝謝,我知道這是一個遲到的反應,但由於某種原因,我總是拼錯這個詞。尤其是當我累了。 原來我正確使用了dup2()。如果我沒有記錯的話,我會在調用fork之前調用它,但這不起作用。 – FatAdama 2012-04-27 01:18:33