在C中自定义shell中的Stdin重定向?

时间:2018-05-28 03:22:13

标签: c shell

所以,基本上,我在C中创建自己的shell,它可以处理重定向。我的stdout重定向工作正常,但我的stdin重定向不起作用。

我试图将stdin重定向到示例:

            hw9> cat < out.txt
            hw9> grep if < out.txt

我的代码:

            if(strcmp(token[i],"<")==0)
            {
                token[i]=NULL;
                int fd0;

                if ((fd0 = open(token[i + 1], O_RDONLY)) < 0)
                {
                    perror("Couldn't open input file");
                    exit(0);
                }
                close(0);
                // dup2() copies content of fdo in input of preceeding file
                dup2(fd0, 0); // STDIN_FILENO here can be replaced by 0

                close(fd0); // necessary
            }

这是我检查和执行stdin重定向的if块,但这似乎不起作用。 cat out.txt的预期输出为"helloo",并且cat < out.txt的输出应该相同,因为重定向将对应cat out.txt。但cat < out.txt并未提供任何输出。文件out.txt的内容为"helloo"

hw9> cat out.txt

Tokens:
[0] 'cat'
[1] 'out.txt'
"helloo"
hw9> cat < out.txt

Tokens:
[0] 'cat'
[1] '<'
[2] 'out.txt'
hw9>

如您所见,第一个调用按预期提供正确的输出,但第二个调用不能证明任何输出。 如果您需要更多信息,请与我们联系。我尝试了多种其他方式,但似乎没有任何效果。提前谢谢!

编辑:我开始工作了!我的错误是在if块之外调用execvp()。我在if-block中调用它,它似乎工作!谢谢你们!

最终代码:

            if(strcmp(token[i],"<")==0)
            {
                token[i]=NULL;
                int fd0;

                if ((fd0 = open(token[i + 1], O_RDONLY)) < 0)
                {
                    perror("Couldn't open input file");
                    exit(0);
                }
                close(0);
                // dup2() copies content of fdo in input of preceeding file
                dup2(fd0, 0); // STDIN_FILENO here can be replaced by 0
                close(fd0); // necessary
                execvp(*token, token);
                perror("execvp");

            }

1 个答案:

答案 0 :(得分:2)

据我所知,你的代码没有任何问题。可能在其他地方出现错误,也许您正在调用Comparator<Map<String, Object>> personComparator = Comparator.comparing(m -> (String) m.get("firstName")) .thenComparing(m -> (String) m.get("lastName")); 。例如,

exec

调用上面的#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int main(int argc, char *argv[]) { int fd0; char *args[3] = { NULL }; args[0] = argv[1]; if (strcmp(argv[2], "<") == 0) { if ((fd0 = open(argv[3], O_RDONLY)) < 0) { perror("open"); exit(1); } dup2(fd0, STDIN_FILENO); close(fd0); execvp(argv[1], args); } else { args[1] = argv[2]; execvp(argv[1], args); } return EXIT_SUCCESS; } 我看到了预期的输出,没有重定向调用,

test.out

并且使用重定向(引用因为shell会自己进行重定向)

./test.out cat test.c