3

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

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被创建但里面什么都没有。我做错了什么?

4

2 回答 2

6

My guess is that the execvp doesn't work but since you don't handler errors you don't see it.

Try this:

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

/* If this is reached execvp failed. */

perror("execvp");

Alternatively you can use compound literals:

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

Second idea: try to run things normally, without redirect and see how it works.

于 2012-01-30T20:18:45.883 回答
1

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

于 2016-11-15T06:47:40.257 回答