繁体   English   中英

如何退出shell程序

[英]How to exit a shell program

我正在制作简单的 shell 程序并尝试在用户输入“exit”时退出它,并且我尝试了一些不同的关键字,例如 exit()、return 0、break;

这是我的代码:

void read_command(char path[], char *args[], char input[]) {
  char *array[MAX], *ptr;

  char *inputptr;
  if ((inputptr = strchr(input, '\n')) != NULL) {
      *inputptr = '\0';
  }

  int i = 0;
  char *p = strtok(input, " ");
  while (p != NULL) {
      array[i++] = p;
      p = strtok(NULL, " ");
  }

  for (int j = 0; j < i; j++) {
      args[j] = array[j];
  }
}

int main() {
  char path[MAX];
  char *args[MAX] = {NULL};
  int status;
  char input[MAX];

  while (TRUE) {
      printf(">> ");
      fgets(input, sizeof(input), stdin);

      if (fork() != 0) {
          if (waitpid(-1, &status, 0) < 0) {
              perror("waitpid error ");
          }

      } else {
          read_command(path, args, input);

          if (strcmp(input, "exit") == 0) {
              exit(0);
          }

          strcpy(path, "/bin/");
          strcat(path, args[0]);

          if (execve(path, args, 0) < 0) {
              perror("exec error ");
              return EXIT_FAILURE;
          }
      }
  }
  return EXIT_SUCCESS;
}

当我返回 strcomp() 值时,它确实给了我 0,所以我不确定为什么它不工作,程序似乎完全忽略了退出语句并继续执行代码,有人可以解释我如何做到这一点吗? 谢谢你。

您在刚刚分叉的子进程中调用exit 相反,读取父进程中的命令,然后退出fork。 顺便说一句,你真的应该检查 fork 没有返回-1

  read_command(path, args, input);

  if (strcmp(input, "exit") == 0)
      /* Don't pass zero here, that's not portable. */
      exit(EXIT_SUCCESS);

  pid_t child;
  switch ((child = fork())) {
      case -1:
         perror("fork failed");
         exit(EXIT_FAILURE);
      case 0:
         // call exec
      default:
          /* Don't pass -1 here if you know which child to wait for.
             Also, you can just pass NULL if to status */
          if (waitpid(child, NULL, 0) < 0)
              perror("waitpid error ");
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM