Advertisement
Guest User

Untitled

a guest
Dec 15th, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. #include <sys/wait.h>
  6.  
  7. char **parse_cmdline(const char *cmdline);
  8.  
  9. int main()
  10. {
  11. int i;
  12. while(1)
  13. {
  14. printf("$ ");
  15.  
  16. char** direction;
  17.  
  18. size_t size=0;
  19. char *suffer = NULL;
  20.  
  21. ssize_t vladi = getline(&suffer,&size,stdin);
  22.  
  23. if( feof(stdin) ) {break;}
  24.  
  25. suffer[strlen(suffer)-1]=' ';
  26.  
  27. direction = parse_cmdline(suffer);
  28. printf("%s",direction[2]);
  29. free(suffer);
  30. pid_t pid = fork();
  31.  
  32. if(pid < 0)
  33. {
  34. perror("fork");
  35. }
  36. else if(pid == 0)
  37. {
  38. int execv_result = execv(direction[0], direction);
  39. if(execv_result == -1)
  40. {
  41. perror(direction[0]);
  42.  
  43. free(direction[0]);
  44. free(direction);
  45. exit(0);
  46. }
  47. exit(0);
  48. }
  49. else
  50. {
  51. waitpid(pid, 0, 0);
  52. }
  53.  
  54. free(direction[0]);
  55. free(direction);
  56. }
  57.  
  58. return 0;
  59. }
  60.  
  61. char **parse_cmdline(const char *cmdline)
  62. {
  63. int size = strlen(cmdline);
  64. char *array = malloc(size * sizeof(char));
  65. strcpy(array, cmdline);
  66.  
  67. int argc = 0;
  68. char **array_of_strings = malloc(sizeof(char*));
  69.  
  70. char *ptr = strtok(array, " ");
  71.  
  72. while (ptr)
  73. {
  74. array_of_strings = realloc(array_of_strings, (argc+1) * sizeof(char*));
  75.  
  76. array_of_strings[argc] = ptr;
  77.  
  78. ptr = strtok(NULL, " ");
  79.  
  80. argc++;
  81. }
  82. array_of_strings[argc] = NULL;
  83.  
  84. return array_of_strings;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement