【问题标题】:Writing a shell in C, closing stdin somewhere用 C 编写一个 shell,在某处关闭标准输入
【发布时间】:2012-04-07 19:01:17
【问题描述】:

我正在编写一个 shell,我似乎在某个时候关闭了标准输入,但我不知道在哪里。我已经倾注了这段代码,但找不到我可能在哪里关闭它。

只有当我使用这样的管道时它才会关闭:

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 */ 

【问题讨论】:

  • 管道结束时关闭标准输入。此时 fgetchar() 应该返回 -1。

标签: c shell pipe system


【解决方案1】:

据我所知,你缺少的是另一个

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

在行处理循环结束之后。你需要练习你的 DRY 纪律(不要重复自己)。

附:你拼错了receive

【讨论】:

  • 谢谢,我知道这是一个迟到的回应,但由于某种原因,我总是拼错这个词。尤其是当我累的时候。原来我正确使用了 dup2() 。如果我没记错的话,我是在调用 fork 之前调用它的,这不起作用。
猜你喜欢
  • 2014-02-22
  • 1970-01-01
  • 2016-07-30
  • 1970-01-01
  • 2018-02-21
  • 2014-06-03
  • 2018-08-29
  • 2011-11-15
  • 1970-01-01
相关资源
最近更新 更多