簡體   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