【发布时间】:2012-05-28 11:37:02
【问题描述】:
我正在构建一个 shell,但系统调用“execvp”遇到了一些问题。我看到了有关此主题的其他一些问题,但它们含糊不清,似乎没有得到完全解决(提出问题的人都没有提供太多信息,也没有得到好的答案)。
显然我有自己的命令行,我正在从标准输入读取用户输入,例如
mysh some/path $ ps -a
我正在构建一个 args 数组作为 char ** 并且数组本身可以工作(我认为),因为当我打印出函数中的值时,它会显示
args[0] = 'ps'
args[1] = '-a'
args[2] = '(null)'
所以,我在我的进程中调用 fork 和 execvp(cmnd, args),其中 cmnd 是“ps”,args 如上所述,以及 perror 等。
我明白了
'Error: no such file or directory.'
我需要放入 $PATH 变量吗?我是不是在做其他奇怪的事情?
这是我生成 args 数组的代码:
char ** get_args(char * cmnd) {
int index = 0;
char **args = (char **)emalloc(sizeof(char *));
char * copy = (char *) emalloc(sizeof(char)*(strlen(cmnd)));
strncpy(copy,cmnd,strlen(cmnd));
char * tok = strtok(copy," ");
while(tok != NULL) {
args[index] = (char *) emalloc(sizeof(char)*(strlen(tok)+1));
strncpy(args[index],tok,strlen(tok)+1);
index++;
tok = strtok(NULL," ");
args = (char**) erealloc(args,sizeof(char*)*(index+1));
}
args[index] = NULL;
return args;
}
(emalloc 和 eralloc 只是 malloc 和 realloc 内置错误检查)
那么我这样做:
void exec_cmnd(char*cmnd, char**args) {
pid_t pid;
if((pid=fork())==0) {
execvp(cmnd, args);
perror("Error");
free(args);
free(cmnd);
exit(1);
}
else {
int ReturnCode;
while(pid!=wait(&ReturnCode)) {
;
}
}
}
就像我上面说的,当在我的进程中调用 execvp 时,当我提供任何参数但没有它们时它会失败(即当 argv == {'ps', NULL} 时)
如果您需要更多信息,请随时询问。我需要解决这个问题。
【问题讨论】:
标签: c shell malloc process execvp