Linux shell上的I / O重定向

时间:2013-10-23 17:39:13

标签: c linux shell io-redirection dup2

正在开发一个shell项目。我已经设置了I / O重定向,但我显然遗漏了一些东西,因为当用以下行测试它时:“ls -al> outfile”它会在我的桌面上创建outfile,但是将它留空并且程序返回以下错误:

ls: >: No such file or directory
Error: Failure to wait for child.
: Interrupted system call

这是我的代码:

        pid_t child = fork();


        if (child < 0)
        {
            perror( "Error: Fork failure.\n" );
            exit(1);
        }

        else if (child == 0)
        {

            //If < file (read)
            if (inpt)
            {
                int fd_in = open(argumnts[index+1], O_RDONLY, 0);
                dup2(fd_in, STDIN_FILENO);
                close(fd_in);
                inpt = 0;
            }

            //If > file (create or truncate)
            if (outpt)
            {
                int fd_out_A = open(argumnts[index+1], O_CREAT | O_TRUNC, 0666); 
                dup2(fd_out_A, STDOUT_FILENO);
                close(fd_out_A);
                outpt = 0;
            }


            execvp (argumnts[0], argumnts);

            perror(command);
            exit(0);
        }
        else
        {
            inpt = 0;
            outpt = 0;
            outptApp = 0;

            if ( waitpid(child, 0, WUNTRACED) < 0 )
                perror( "Error: Failure to wait for child.\n" );
        }
    }

} //End While(1) loop

比较器函数只检查输入的命令参数是“&lt;”,“&gt;”还是“&gt;&gt;”,然后返回包含它的索引。

不确定我在这里缺少什么,但它会回复之前提到的错误。有什么想法吗?

1 个答案:

答案 0 :(得分:3)

有两个单独的事情发生。

    在调用ls: >: No such file or directory之前,可以通过设置argumnts[index]=NULL来修复
  1. execvpls> outputfile视为应列出的其他文件名。终止参数列表的NULL将处理这个问题。

  2. Error: Failure to wait for child. : Interrupted system call:等待时发生了一些事情。中断的系统调用(EINTR)通常不是问题,可以重新启动而不会产生任何不良影响。我发现以下建议here将单个来电替换为waitpid

  3.   

    “典型的代码序列是:

       while((pid = waitpid(,,)) == -1) {
    
           switch (errno) {
    
           case EINTR: continue;
    
           default: printf(stderr, ...)
    
                   break;
    
           }}
    
       ... rest of normal waitpid-hanling goes here ...
    
         

    此外,您可能必须至少为SIGCHLD安装一个signalhandler。 “

    另外,我注意到你没有重定向stderr,这可能会导致父母和孩子之间的交互。另一个问题 - 你是否击中了控制-C?如果是,请参阅here

    此外,WUNTRACED可能是也可能不是您要指定的内容,具体取决于您是否正在处理终端信号。请参阅waitpid(2)的联机帮助页,例如here。也许0WEXITED