Minishell problems with cd (C)

2020-05-06 10:47发布

问题:

I made a simple minishell in C and it works, except for the cd command. When I try to run it nothing happens except it creates a child process that never actually ends. For example, after running cd in my minishell I need to type exit twice to exit the minishell, not the standard once. Code: int debug=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);
  }
    }
}

回答1:

cd is necessarily a shell built-in, not an external utility. You want to change the current working directory of the current process (the shell itself), not of a child process. Call chdir instead of forking a child process.

Separately, check execvp for errors and defensively terminate the child after a failed exec. You'd have seen an informative error if you had done so:

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


标签: c linux fork