使用execvp

时间:2015-06-03 06:53:06

标签: c exec fopen io-redirection dup2

我正在尝试将输出从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] = '\0';
                        }
                        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

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

2 个答案:

答案 0 :(得分:1)

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

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

如果你想这样做,你需要使用system电话。见System(3)

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

答案 1 :(得分:0)

            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,这显然是不正确的。您需要从参数中删除它。

相关问题