【发布时间】:2016-04-29 03:11:29
【问题描述】:
我正在用 C 语言编写一个简单的 shell 程序,我相信我已经完成了。该程序应不断打印“提示>”并等待用户输入可执行文件的名称以及可执行文件所需的任何参数。 shell只有一个内置函数quit,它结束程序。如果用户要在行尾添加一个“&”,那么给定的可执行文件应该在后台运行。 (没有'&'的内置函数和命令应该在前台运行并等待子进程完成。)但是,当我运行我的代码并在我的行尾放置一个'&'时,可执行文件运行并且完成,但我不再看到“提示>”出现。我仍然可以输入可执行文件的名称或退出,它会运行和一切,但我不明白为什么提示没有出现。
也是一个附带问题。我的程序是否正确处理子进程?基本上,我不会用这段代码离开僵尸进程吗?
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#define MAXBUFF 100
#define MAXLINE 200
int parse_line(char *buffer, char **arg_array);
void evaluate_commandline(char *commandline);
int builtin_command();
int parse_line(char *buffer, char **arg_array){
char *delimiter;
int num_args;
int run_background;
buffer[strlen(buffer)-1] = ' ';
while(*buffer && (*buffer == ' '))
buffer++;
num_args = 0;
while((delimiter = strchr(buffer, ' '))){
arg_array[num_args++] = buffer;
*delimiter = '\0';
buffer = delimiter + 1;
while(*buffer && (*buffer == ' '))
buffer++;
}
arg_array[num_args] = NULL;
if(num_args == 0)
return 1;
if((run_background = (*arg_array[num_args-1] == '&')) != 0)
arg_array[--num_args] = NULL;
return run_background;
}
void evaluate_commandline(char *commandline){
char *arg_array[MAXBUFF];
char buffer[MAXLINE];
int run_background;
pid_t pid;
strcpy(buffer, commandline);
run_background = parse_line(buffer, arg_array);
if(arg_array[0] == NULL)
return;
if(!builtin_command(arg_array)){
if((pid = fork())== 0){
if(execvp(arg_array[0],arg_array)< 0){
printf("%s: Command not found.\n", arg_array[0]);
exit(0);
}
}
if(!run_background){
int child_status;
wait(&child_status);
}
}
return;
}
int builtin_command(char **arg_array){
if(!strcmp(arg_array[0],"quit"))
exit(0);
return 0;
}
int main(){
char commandline[MAXLINE];
while(1){
printf("prompt> ");
fgets(commandline, MAXLINE, stdin);
if(feof(stdin))
exit(0);
evaluate_commandline(commandline);
}
}
【问题讨论】:
标签: shell process wait zombie-process