File 将stdout重定向到fork()之后的文件

File 将stdout重定向到fork()之后的文件,file,fork,redirect,stdout,dup2,File,Fork,Redirect,Stdout,Dup2,我正在开发一个简单的shell,但现在我只是想了解重定向。我只是硬编码一个ls命令,并尝试将其写入一个文件。目前,ls运行,并创建输出文件,但输出仍将转到stdout,文件为空。我不明白为什么。提前谢谢 这是我的密码: int main() { int ls_pid; /* The new process id for ls*/ char *const ls_params[] = {"/bin/ls", NULL}; /* for ls */ int file; /* f

我正在开发一个简单的shell,但现在我只是想了解重定向。我只是硬编码一个ls命令,并尝试将其写入一个文件。目前,ls运行,并创建输出文件,但输出仍将转到stdout,文件为空。我不明白为什么。提前谢谢

这是我的密码:

int main()
{
    int ls_pid; /* The new process id for ls*/
    char *const ls_params[] = {"/bin/ls", NULL}; /* for ls */
    int file; /* file for writing */

    /* Open file check user permissions */
    if (file = open("outfile", O_WRONLY|O_CREAT) == -1) /* , S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP */
    {
        perror("Failed to open file");
        _exit(EXIT_FAILURE);
    } 

    ls_pid = fork(); /* Create new process for ls */

    if (ls_pid == -1) /* error check */
    {
        perror("Error forking ls (pid == -1)");
        _exit(EXIT_FAILURE);
    }
    else if (ls_pid == 0) /* Child of ls */
    {
        /* Redirect output to file */
        if (dup2(file, STDOUT_FILENO) == -1) /* STDOUT_FILENO = 1 */
        {
            perror("Error duping to file");
            _exit(EXIT_FAILURE);
        }
        close(file);

        execvp("ls", ls_params); /* create the sort process */
        /* execlp("ls", "ls", NULL); */

        /* if this does not end the program, something is wrong */
        perror("Exec failed at sort");
        _exit(EXIT_FAILURE);
    }
    else /* ls parent (1) */
    {
        /* wait for child */
        if (wait(NULL) == -1)
        {
            perror("fork failed on parent");
            _exit(EXIT_FAILURE);
        }
    }

}

我看没什么问题。我自己试过你的代码。而且它有效!我的简化代码如下所示:

int main(void) {
    int fd;

    char* const param[] = {"/bin/ls", NULL};

    fd = open("outfile", O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);

    if (fd < 0) {
        perror("open failed\n");
        exit(0);
    }

    pid_t pid = fork();

    if (pid < 0) {
        perror("fork failed\n");
        exit(0);
    }
    else if (pid == 0) {
        dup2(fd, STDOUT_FILENO);

        close(fd);

        execvp("ls", param);
    }
    else {
        wait(NULL);
    }
}
int main(无效){
int-fd;
char*const param[]={“/bin/ls”,NULL};
fd=开放(“输出文件”,O|u WRONLY | O|u CREAT,S|u IRUSR | S|u IWUSR);
如果(fd<0){
perror(“打开失败\n”);
出口(0);
}
pid_t pid=fork();
if(pid<0){
perror(“fork失败\n”);
出口(0);
}
否则如果(pid==0){
dup2(fd,标准文件号);
关闭(fd);
execvp(“ls”,参数);
}
否则{
等待(空);
}
}
我编译并执行它,并在outfile中找到预期的结果


唯一的区别是,我使用S|u IRUSER | S|u IWUSER权限选项提供open,因为否则,open将失败。我在您的代码中看到了类似的东西,但不知何故您对它们进行了注释…

已修复。这是我的公开命令。