我在 C 中做了一个简单的 minishell,它可以工作,除了cd
命令。当我尝试运行它时,除了它创建一个永远不会真正结束的子进程之外,什么也没有发生。例如,cd
在我的 minishell 中运行后,我需要输入exit
两次才能退出 minishell,而不是标准的一次。代码:int调试=0;
void safeQuit(){
if (debug==1)
printf("INFO: Parent process, pid=%d exiting.\n", getpid());
exit(0);
}
int main(int argc,char** argv)
{
int pid, stat;
char * Array_arg[50];
char command_line[200];//user input
if (argc>1)
if (strcmp(argv[1],"-debug")==0)
debug=1;
while (1){
printf("[minishell]> "+debug);
gets(command_line);
if (strcmp(command_line,"exit")==0)
safeQuit();
char * subcommand=strtok(command_line," "); //divides the string according to the spaces
int i=0;
while (subcommand!= NULL)//insert to array
{
Array_arg[i]=subcommand;
subcommand=strtok(NULL," ");
i++;
}
Array_arg[i]='\0';
if (fork()==0){
if (debug==1)
printf("INFO: child process, pid = %d, executing command %s\n", getpid(), command_line);
execvp(Array_arg[0],Array_arg); //execution of cmd
}
else{
pid=wait(&stat);
}
}
}