C:execv之前的dup2() [英] C: dup2() before execv
问题描述
对于家庭作业,我必须编写一个包括重定向的基本shell.该程序使用readline提示输入,解析输入字符串,并将其分解为可执行文件名称,参数和输入/输出文件(如果适用).解析完字符串后,它将分叉并将子execv()传递到传入的可执行文件中.我正在使用dup2()来更改分叉之后和execv之前的文件描述符,但是一旦程序已执行到新的可执行文件.如果在我的shell中运行ls > foo.out
,则得到:ls: cannot access H��y�A�
$ L��H)�I��$�: No such file or directory
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
c-> argv的构造:
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);
推荐答案
您如何构建c->argv
?它必须是NULL
终止的char *
数组.您可能会错过终止符.
How are you constructing c->argv
? It must be a NULL
-terminated array of char *
. You are likely missing the terminator.
在处理<...
和>...
的代码中,您跳过了argv
中的一个条目,而未初始化.
In your code handling <...
and >...
, you skip over an entry in argv
, leaving it uninitialized.
这篇关于C:execv之前的dup2()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!