shell.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #define BUFFER_SIZE 1024
  5. #define TOKEN_SIZE 64
  6. #define TOKEN_DELIM " \t"
  7. char *read_input()
  8. {
  9. printf("> ");
  10. int buf_size = BUFFER_SIZE;
  11. char* buf = malloc(buf_size * sizeof(char));
  12. int c;
  13. char pos = 0;
  14. while(1) {
  15. c = getchar();
  16. if(c == EOF || c == '\n') {
  17. buf[pos] = '\0';
  18. return buf;
  19. }
  20. buf[pos++] = c;
  21. if(pos >= 1024) {
  22. buf_size *= 2;
  23. buf = realloc(buf, buf_size * sizeof(char));
  24. }
  25. }
  26. }
  27. char **tokenize(char *input)
  28. {
  29. int position = 0, buf_size = TOKEN_SIZE;
  30. char **tokens = malloc(buf_size * sizeof(char*));
  31. char *token = strtok(input, TOKEN_DELIM);
  32. while(token != NULL) {
  33. tokens[position++] = token;
  34. if(position >= buf_size) {
  35. buf_size *= 2;
  36. tokens = realloc(tokens, buf_size * sizeof(char*));
  37. }
  38. token = strtok(NULL, TOKEN_DELIM);
  39. }
  40. tokens[position] = '\0';
  41. return tokens;
  42. }
  43. int execute(char* args)
  44. {
  45. pid_t pid, wpid;
  46. int status;
  47. pid = fork();
  48. if(pid == 0) {
  49. //child process;
  50. if(execvp(args[0], args) == -1) {
  51. perror("error while executing command in child process");
  52. }
  53. exit(0);
  54. } else if(pid < 0) {
  55. perror("error while forking");
  56. } else {
  57. //master process
  58. do {
  59. wpid = waitpid(pid, &status, WUNTRACED);
  60. } while(!WIFEXITED(status) && !WIFSIGNALED(status));
  61. }
  62. return 1;
  63. }
  64. int main()
  65. {
  66. while(1) {
  67. char *input = read_input();
  68. if(strcmp(input, "exit") == 0) {
  69. printf("Bye!\n");
  70. return 0;
  71. }
  72. char **tokenized = tokenize(input);
  73. printf("Your command is %s, %lu tokens\n", input, (sizeof(tokenized)/sizeof(tokenized[0])));
  74. free(input);
  75. free(tokenized);
  76. }
  77. }