【问题标题】:How to exit a shell program如何退出一个shell程序
【发布时间】:2020-11-07 19:25:11
【问题描述】:

我正在制作简单的 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,所以我不确定为什么它不工作,程序似乎完全忽略了退出语句,只是继续执行代码,有人可以解释一下我该怎么做这?谢谢。

【问题讨论】:

  • 记住,当你分叉时,你有两个进程从另一边出来。他们都需要退出。

标签: c linux bash shell system-calls


【解决方案1】:

您在刚刚分叉的子进程中调用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 ");
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-24
    • 1970-01-01
    相关资源
    最近更新 更多