C: dup2() before execv

2019-06-12 08:11发布

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: cannot access H��y�A� $ L��H)�I��$�: No such file or directory

Construction of c->argv:

char *args[6];

int i;
for(i=0;i<=4;i++){
    char *_arg=strsep(&_str_cmd," ");
    printf("Found _arg: %s\n",_arg);

    // If there is an argument and it is not blank
    if(_arg && strcmp(_arg,"")!=0){
        if(strcmp(_arg,"<")==0){
            _cmd.infile=strsep(&_str_cmd," ");
            i--;
            continue;
        }
        else if(strcmp(_arg,">")==0){
            _cmd.outfile=strsep(&_str_cmd," ");
            i--;
            continue;
        }
    }
    else{break;}
}
args[i]=(char*)0;

_cmd.binary=args[0];
memcpy(_cmd.argv,args,sizeof _cmd.argv);

1条回答
贪生不怕死
2楼-- · 2019-06-12 08:52

How are you constructing c->argv? It must be a NULL-terminated array of char *. You are likely missing the terminator.


In your code handling <... and >..., you skip over an entry in argv, leaving it uninitialized.

查看更多
登录 后发表回答