简体   繁体   中英

C: dup2() before execv

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM