[英]Stdin redirection in custom shell in C?
因此,基本上,我正在用C创建自己的shell,该shell可以处理重定向。 我的stdout重定向有效,但我的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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.