use*_*954 3 c redirect file 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 被创建但里面什么都没有。我做错了什么?
我的猜测是 execvp 不起作用,但由于您不处理错误,因此您看不到它。
尝试这个:
char *const args[] = {"ls", NULL};
execvp(args[0], args);
/* If this is reached execvp failed. */
perror("execvp");
或者,您可以使用复合文字:
execvp("ls", (char *[]){"ls", NULL});
第二个想法:尝试正常运行,没有重定向,看看它是如何工作的。