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

Receiving error code during output redirection using 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 <= count; i++)
                    {   if(i == count)
                        {
                            args[i] = (char *)malloc(2 * sizeof(char));
                            args[i] = '[=13=]';
                        }
                        else
                        {
                            str = strlen(string[i]);
                            args[i] = malloc(str);
                            strcpy(args[i], string[i]);                     
                        }
                    }                       

                if(count == 1)
                {

                }
                else if(strcmp(string[(numargs + 1)], ">") == 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

创建了名为垃圾的文件,但放入其中的所有内容都是垃圾。我已经为此苦苦挣扎了一段时间,所以非常感谢任何帮助弄清楚为什么重定向不起作用的帮助。谢谢。

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

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

如果你想这样做,你需要使用 system 调用。参见 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,这显然是不正确的。您需要将其从参数中删除。