C: execv 之前的 dup2()
对于家庭作业,我必须编写一个包括重定向在内的基本 shell。该程序使用 readline 提示输入,解析输入字符串,并将其分解为可执行文件名称、参数和输入/输出文件(如果适用)。解析字符串后,它分叉并将子 execv() 传递给传入的可执行文件。我使用 dup2() 来更改分叉之后和 execv 之前的文件描述符,但是一旦程序已 execv'd 为新的可执行文件。如果在我的 shell 中运行 ls > foo.out
,我得到:ls:无法访问 H��y�A� $ L��H)�I��$�: 没有这样的文件或目录
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);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你是如何构建
c->argv
的?它必须是一个以NULL
结尾的char *
数组。你可能错过了终结者。在处理
<...
和>...
的代码中,您跳过了argv
中的条目,使其处于未初始化状态。How are you constructing
c->argv
? It must be aNULL
-terminated array ofchar *
. You are likely missing the terminator.In your code handling
<...
and>...
, you skip over an entry inargv
, leaving it uninitialized.