开发者

C: `write error: Bad file descriptor` after fork, dup2, and execv

开发者 https://www.devze.com 2023-02-16 16:59 出处:网络
Continuing on this problem, but I\'ll reiterate: For a homework assignment I have to write a basic shell including redirection. The program uses readline to prompt for input, parses the input string

Continuing on this problem, but I'll reiterate:

For a homework assignment I have to write a basic shell including redirection. The program uses readline to prompt for input, parses the input string, and breaks it down into the executable name, the arguments, and the input/output file(s), if applicable. After parsing the string, it forks and the child execv()'s to the executable that was passed in. I'm using dup2() to change the file descriptors after the fork and before the execv, but am having a problem once the program has execv'd to the new executable. If in my shell I run ls > foo.out, I get: ls: write error: Bad file descriptor

开发者_开发百科Here is the code for my child process (this is after 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;
        }
    }

I do not get the "Failed to redirect command output." error. As I mentioned, this is a homework assignment so I'm not looking for anyone to fix this, but rather point me in the right direction.


The problem is in this bit of code:

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

You should be closing fd, not 1. You have the same problem in the fd 0 case, too.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号