在 C 语言中的自定义外壳中重定向 Stdin 重定向?



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

我正在尝试重定向 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
}

这是我的 if 块来检查和执行 stdin 重定向,但这似乎不起作用。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 块中调用它,它似乎有效!谢谢大家!

最终代码:

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");
}

据我所知,您的代码没有任何问题。错误可能出在其他地方,也许您正在呼叫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我看到了预期的输出,无需重定向即可调用,

./test.out cat test.c

并带有重定向(引用是因为 shell 会执行自己的重定向(

./test.out cat '<' test.c

最新更新