首页 > 解决方案 > 如何在 C 中的 io 重定向后返回标准输入/输出

问题描述

我正在用 C 创建一个简单的 shell,其中一个功能是 IO 重定向。然而; 在完成重定向命令的执行后,我很难弄清楚如何返回标准输入/标准输出。

我尝试复制标准输入/输出,然后在主函数中再次使用它,如代码所示,但这不起作用。

void  execute(char **args, bool flag)
{
    pid_t  pid;
    int status;
    int exc;

    if ((pid = fork()) < 0) {     
        printf("forking child process failed\n");
    }

    else if (pid == 0) {          /* for the child process:         */
        if(in_flag){
            file_desc_in = open(sub2, O_RDONLY | O_CREAT);
            chmod(sub2 , S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH);
            stdinCopy = dup(STDIN_FILENO);
            dup2(file_desc_in, 0);
            close(file_desc_in);    
            in = true;

        }
        else if(out_flag){
            file_desc_out = open(sub2,O_WRONLY |O_APPEND | O_CREAT);
            chmod(sub2 , S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH);
            stdoutCopy = dup(STDOUT_FILENO);
            dup2(file_desc_out, STDOUT_FILENO);
            close(file_desc_out);           
            out = true;

        }
        exc =  execvp(args[0], args);     /* execute the command  */

        printf("exec failed!\n")
        exit(EXIT_FAILURE)

    }

    if(flag){
        pid_t childpid = wait(&status);
    }

}

这部分在 main()

if(out){
        dup2(stdoutCopy,STDOUT_FILENO);
        close(stdoutCopy);
        out = false;    
    }
    else if(in){
        dup2(stdinCopy,STDIN_FILENO);
        close(stdinCopy);
        in = false; 
    }

例如,当我将 ls 命令的输出重定向到某个文件 output.txt 时,重定向会起作用并且输出会显示在文件中,但是对于所有新输入的命令,所有输出都会转到同一个文件,而不是显示在终端上。

我该如何解决这个问题?

标签: coperating-systemio-redirection

解决方案


推荐阅读