2012-04-07 66 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