【问题标题】:C: `write error: Bad file descriptor` after fork, dup2, and execvC: `write error: Bad file descriptor` 在 fork、dup2 和 execv 之后
【发布时间】:2011-03-11 03:49:17
【问题描述】:

继续this problem,但我会重申:

对于家庭作业,我必须编写一个基本的 shell,包括重定向。该程序使用 readline 提示输入,解析输入字符串,并将其分解为可执行文件名称、参数和输入/输出文件(如果适用)。解析字符串后,它分叉并将子 execv() 分配给传入的可执行文件。我使用 dup2() 在分叉之后和 execv 之前更改文件描述符,但是一旦出现问题程序已执行到新的可执行文件。如果在我的 shell 中运行 ls > foo.out,我会得到:ls: write error: Bad file descriptor

这是我的子进程的代码(这是在 fork() 之后):

int _child(struct command *c){
    int ret;
    /* When given `ls > foo.out`, these next two lines output:
    ** c->infile is (null)
    ** c->outfile is foo.out
    */
    printf("c->infile is %s\n",c->infile);
    printf("c->outfile is %s\n",c->outfile);
    if(c->infile){
        int fd = open( c->infile, O_RDONLY);
        int _fd_dup = dup2(fd,0);
        close(0);
        if(_fd_dup != 0){
            fprintf(stderr, "Failed to redirect command input.\n");
            return 0;
        }
    }
    if(c->outfile){
        int fd = open( c->outfile, O_WRONLY | O_CREAT | O_TRUNC, 0600);
        int _fd_dup = dup2(fd,1);
        close(1);
        if(_fd_dup != 1){
            fprintf(stderr, "Failed to redirect command output.\n");
            return 0;
        }
    }

我没有收到“无法重定向命令输出”。错误。正如我所提到的,这是一项家庭作业,所以我不是在寻找任何人来解决这个问题,而是为我指明正确的方向。

【问题讨论】:

    标签: c exec fork file-descriptor


    【解决方案1】:

    问题出在这段代码中:

        int _fd_dup = dup2(fd,1);
        close(1);
    

    您应该关闭fd,而不是1。你在 fd 0 的情况下也有同样的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多