我试图了解有关Unix的更多信息并在C中编写shell。我的execute()命令替换了函数system(),它适用于ls,clear等命令。但是,我可以& #39; t让它适用于cat命令。相反,每次错误消息的数量都会翻倍(见下文)。
==>cat
==>a
==>error in child==>a
a
a
==>error in child==>a
==>error in child==>a
a
a
==>error in child==>a
==>error in child==>a
==>error in child==>a
==>error in child==>a
a
a
==>error in child==>a
==>error in child==>a
==>error in child==>a
==>error in child==>a
==>error in child==>a
==>error in child==>a
==>error in child==>a
==>error in child==>a
a
a
这是execute()命令。如果我在使用execute()的任何地方使用system(),cat效果很好,但是使用execute(),它不会。在输入的命令仅为cat
的情况下,args[0]
为cat
且args[1]
为空终止符。长度为1.
int execute (char** args)
{
int status;
pid_t pid;
switch(pid = fork())
{
case -1:
status = -1;
fprintf(stderr, "failed to fork");
break;
case 0:
execvp(args[0], args);
fprintf(stderr,"error in child");
default:
if(!WIFSIGNALED(status) && !WIFEXITED(status))
waitpid(pid, &status, WUNTRACED);
}
return 0;
}
这就是在main()方法中使用execute()的方法。来自键盘的命令存储为cmndbuf中的字符串(声明为char cmndbuf[MAX_BUFFER]
)。然后将cmndbuf拆分并放入名为splits的新数组中。
if (cmndbuf[0]){
char** splits=malloc(sizeof(char*)*MAX_BUFFER + 1);
int i;
char* to_sep=cmndbuf;
for(i=0; i<MAX_ARGS; i++)
{
splits[i] = strsep(&to_sep, " ");
if(splits[i]==NULL) break;
}
execute(splits);
//system(cmndbuf); //this works
free(splits);
}
谢谢你们! :)
答案 0 :(得分:0)
行
if(!WIFSIGNALED(status) && !WIFEXITED(status))
waitpid(pid, &status, WUNTRACED);
由于waitpid()需要执行至少一次,然后需要不断执行,直到条件变为false,否则无法工作。也就是说,需要一个do-while循环:
do {
wpid = waitpid(pid, &status, WUNTRACED);
} while (!WIFEXITED(status) && !WIFSIGNALED(status));