在下一个shell提示符后显示Unix命令输出
问题描述:
我正在使用C语言编写一个用于学校项目的shell,但这个问题比您想象的要少得多。问题在于,当我输入命令时,例如ls
,输出显示在整个shell循环开始时显示的下一个shell>
提示之后。外壳看起来像:在下一个shell提示符后显示Unix命令输出
shell>ls
shell>Debug shell.c
我的代码:
int main(){
char line[255];
while (1){
printf("shell>");
fgets(line, 255, stdin);
if (strcmp(line, "exit\n") == 0){
break;
}
else{
char* args[255];
size_t n = 0;
for (char* ptr = strtok(line, " \n"); ptr; ptr = strtok(NULL, " \n")){
if (n >= 255){
break;
}
args[n++] = ptr;
}
args[n++] = NULL;
for (size_t i = 0; i != n; ++i){
//printf("Token %zu is '%s'.\n", i, args[i]);
}
int pid = fork();
if (pid == 0){
//child process code
int flag = execvp(args[0], args);
if (flag < 0){
perror("execvp failed");
}
}
else{
//parent process code
pid_t wait_pid(pid);
}
}
}
return 0;
}
所有其他错误之外,是什么导致要显示的输出这样?
答
pid_t wait_pid(pid);
是错的,它不叫wait_pid
。在调用函数时,您不指定返回类型。相反,尝试:
pid_t result_pid = wait_pid(pid);
// add error handling etc here, check man page for return value details
而且因为你实际上并没有等待孩子的过程中,家长进行立即打印提示,为您看到的输出。
谢谢,清理了一些东西 – 2014-09-28 19:11:23