CD的Minishell问题(C) [英] Minishell problems with cd (C)

查看:101
本文介绍了CD的Minishell问题(C)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用C语言制作了一个简单的minishell,除了cd命令之外,它都可以工作.当我尝试运行它时,除了创建从未真正结束的子进程外,什么都没有发生.例如,在我的迷你外壳程序中运行cd后,我需要两次键入exit退出迷你外壳程序,而不是标准一次. 代码: int debug = 0;

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

推荐答案

cd必须是内置的Shell,而不是外部实用程序.您想要更改当前进程(shell本身)而不是子进程的当前工作目录.呼叫 chdir 而不是派生子进程.

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.

另外,检查execvp是否存在错误,并在 exec 失败后以防御方式终止子级.如果这样做,您将看到一个提示性错误:

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

这篇关于CD的Minishell问题(C)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆