C: dup2() before execv

若如初见. 提交于 2019-12-08 11:53:57

问题


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:


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.



来源:https://stackoverflow.com/questions/5268583/c-dup2-before-execv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!