使用execvp在输出重定向期间接收错误代码

我试图将输出从ls重定向到我在C中创建的shell中的文件。我输入:

 ls > junk 

我得到的是:

 ls: cannot access >: No such file or directory 

然后,如果我使用CTRL-D退出shell,它会在退出之前将ls命令的结果打印到屏幕。 我尝试使用print语句来确定它发生的位置,并且在以下情况之后不打印任何打印语句:

 dup2(f, STDOUT_FILENO); Also tried dup2(f, 1); 

码:

  pid = fork(); if(pid == 0) { // Get the arguments for execvp into a null terminated array for(i = 0; i ") == 0) //numargs is the number of arguments typed in by the user { // printed out string[numargs+2] previously, and it says junk int f = open(string[(numargs + 2)], O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if(f < 0) { printf("Unable to open output file\n"); status = 1; } else { fflush(stdout); dup2(f, STDOUT_FILENO); close(f); } } j = execvp(string[0], args); // The first element of the string array is the first thing the user enters which is the command ls in this case 

创建了一个名为junk的文件,但放在其中的所有内容都是垃圾。 我一直在努力解决这个问题,所以任何帮助搞清楚为什么重定向不起作用都会非常感激。 谢谢。

您不能使用execvp来解析shell命令。

shell可以理解重定向(>)字符(例如, bashshksh ), execvp执行直接传递它的命令。 它不会尝试解释参数并创建文件重定向等。

如果要这样做,则需要使用system调用。 见系统(3)

同样,任何其他特殊shell字符(管道,*,?,&等)都不起作用。

  j = execvp(string[0], args); // The first element of the string array is the first thing the user enters which is the command ls in this case 

这会将>传递给execvp ,这显然是不正确的。 您需要从参数中删除它。