2013-05-21 41 views
0

我做了一个简单的minishell在C和它的作品,除了cd命令。当我尝试运行它时,除了创建一个从未实际结束的子进程之外,没有任何事情发生。例如,在我的迷你版中运行cd之后,我需要输入exit两次以退出minishell,而不是标准一次。代码: int debug = 0;Minishell问题与光盘(C)

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); 
    } 
    } 
} 

回答

2

cd必然是内置的外壳,而不是外部的实用程序。你想改变当前进程的当前工作目录(shell本身),而不是子进程。致电chdir而不是分叉子进程。

另外,检查execvp错误和防守失败EXEC后终止了孩子。如果您这样做了,您会看到一条信息错误:

... (child) ... 
execvp(Array_arg[0], Array_arg); 
perror("Error - exec failed"); // If we are here, we did *not* replace the process image 
exit(0);