shell.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. #include <libc/unistd.h>
  2. #include <libc/stdio.h>
  3. #include <libc/fcntl.h>
  4. #include <libc/stdlib.h>
  5. #include <libKeyboard/keyboard.h>
  6. #include <libc/string.h>
  7. #include <libc/stddef.h>
  8. #include "cmd.h"
  9. #define pause_cpu() asm volatile("pause\n\t");
  10. /**
  11. * @brief 循环读取每一行
  12. *
  13. * @param fd 键盘文件描述符
  14. * @param buf 输入缓冲区
  15. * @return 读取的字符数
  16. */
  17. int shell_readline(int fd, char *buf);
  18. extern char *shell_current_path;
  19. /**
  20. * @brief shell主循环
  21. *
  22. * @param kb_fd 键盘文件描述符
  23. */
  24. void main_loop(int kb_fd)
  25. {
  26. unsigned char input_buffer[INPUT_BUFFER_SIZE] = {0};
  27. // 初始化当前工作目录的路径
  28. shell_current_path = (char *)malloc(3);
  29. memset(shell_current_path, 0, 3);
  30. shell_current_path[0] = '/';
  31. shell_current_path[1] = '\0';
  32. // shell命令行的主循环
  33. while (true)
  34. {
  35. int argc = 0;
  36. char **argv;
  37. printf("[DragonOS] %s # ", shell_current_path);
  38. memset(input_buffer, 0, INPUT_BUFFER_SIZE);
  39. // 循环读取每一行到buffer
  40. int count = shell_readline(kb_fd, input_buffer);
  41. if (count)
  42. {
  43. int cmd_num = parse_command(input_buffer, &argc, &argv);
  44. printf("\n");
  45. if (cmd_num >= 0)
  46. shell_run_built_in_command(cmd_num, argc, argv);
  47. }
  48. else
  49. printf("\n");
  50. }
  51. }
  52. int main()
  53. {
  54. // 打开键盘文件
  55. char kb_file_path[] = "/dev/keyboard.dev";
  56. int kb_fd = open(kb_file_path, 0);
  57. // printf("keyboard fd = %d\n", kb_fd);
  58. main_loop(kb_fd);
  59. while (1)
  60. ;
  61. }
  62. /**
  63. * @brief 循环读取每一行
  64. *
  65. * @param fd 键盘文件描述符
  66. * @param buf 输入缓冲区
  67. * @return 读取的字符数
  68. */
  69. int shell_readline(int fd, char *buf)
  70. {
  71. int key = 0;
  72. int count = 0;
  73. while (1)
  74. {
  75. key = keyboard_analyze_keycode(fd);
  76. if (key == '\n')
  77. return count;
  78. if (key)
  79. {
  80. if (key == '\b')
  81. {
  82. if (count > 0)
  83. {
  84. buf[--count] = 0;
  85. printf("%c", '\b');
  86. }
  87. }
  88. else
  89. {
  90. buf[count++] = key;
  91. printf("%c", key);
  92. }
  93. }
  94. // 输入缓冲区满了之后,直接返回
  95. if (count >= INPUT_BUFFER_SIZE - 1)
  96. return count;
  97. pause_cpu();
  98. }
  99. }