将execvp的输出重定向到C中的文件

时间:2012-01-30 20:15:39

标签: c file redirect execv

我不知道我做错了什么......但这里是正在执行的代码片段:

if (fork() == 0)
    {       
             // child
        int fd = open(fileName, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);

        dup2(fd, 1);   // make stdout go to file

        execvp("ls","ls");
        close(fd);
            exit(0);
    }
if(wait(&status) == -1)
    {
        printf("ERROR REDIRECT\n");
    }

fileName被创建但内部没有任何内容。我做错了什么?

2 个答案:

答案 0 :(得分:4)

我的猜测是execvp不起作用,但由于你没有处理错误,所以你看不到它。

试试这个:

char *const args[] = {"ls", NULL};
execvp(args[0], args);

/* If this is reached execvp failed. */

perror("execvp");

或者,您可以使用复合文字:

execvp("ls", (char *[]){"ls", NULL});

第二个想法:尝试正常运行,没有重定向,看看它是如何工作的。

答案 1 :(得分:0)

在execvp之前关闭fd。 因为除非execvp失败,否则execvp之后的代码永远不会运行。