繁体   English   中英

在 C 中写入 shell,在某处关闭标准输入

[英]Writing a shell in C, closing stdin somewhere

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

只有当我像这样使用 pipe 时它才会关闭:

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

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

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

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

PS 你拼错了 receive

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM