我正在尝试在我为类 Unix 操作系统 (xV6) 编写的 shell 中实现 I/O 重定向。在我为操作系统阅读的手册中,我发现以下代码将在 shell 中运行以执行 cat 命令:
char *argv[2];
argv[0] = "cat";
argv[1] = 0;
if(fork() == 0) {
close(0);
open("input.txt", O_RDONLY);
exec("cat", argv);
}
Run Code Online (Sandbox Code Playgroud)
我修改了代码以在我的 shell 中运行,它的 argv 数组位于另一个函数中,但它保持了功能。出于某种原因,当我运行cat < input.txtshell 输出时:
cat: -: Bad file descriptor
cat: closing standard input: Bad file descriptor
Run Code Online (Sandbox Code Playgroud)
我还是 OS 编程的新手,所以我对 I/O 重定向的所有功能不是很清楚,但我认为我拥有的代码应该可以工作。什么可能导致问题。我有下面的 I/O 重定向代码:
case '<':
ecmd = (struct execcmd*)cmd;
rcmd = (struct redircmd*)cmd;
if(fork() == 0){
close(0);
open("input", O_RDONLY);
execvp(ecmd->argv[0], ecmd->argv );
} …Run Code Online (Sandbox Code Playgroud)