Advertisement
Guest User

Untitled

a guest
Jan 21st, 2018
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 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. size_t size=0; // razmera na prochetenoto
  12. char *suffer = NULL; // tuka she se zapishe tova koeto prochete getline
  13. while(1)
  14. {
  15. printf("$ ");
  16.  
  17. ssize_t vladi = getline(&suffer,&size,stdin);//vrusta kolko e prochelo , - 1 pri EOF ili greshka
  18.  
  19. if( feof(stdin) ) {break;}
  20.  
  21. char** direction; //tuka pazim kakvoot vurne parse_cmdline
  22.  
  23. suffer[strlen(suffer)-1]='\0'; /// mahame noviq red koito getline procheti sushto osven tova koeto e napisano
  24.  
  25. direction = parse_cmdline(suffer);
  26.  
  27. pid_t pid = fork(); // prvai nov proces
  28.  
  29. if(pid < 0)
  30. {
  31. perror("fork");
  32. }
  33. else if(pid == 0)
  34. {
  35. int execv_result = execv(direction[0], direction);// ako se izpulni zamenq koda na procesa sus tozi na koito execvame
  36. if(execv_result == -1)// ako ima greshka ne zamenq koda
  37. {
  38. perror(direction[0]);
  39. free(direction[0]);
  40. free(direction);
  41. free(suffer);
  42. exit(0);
  43. }
  44. exit(0);//nenuzen exit tui kato ne moze da bude dostignat. ako exec proraboti to koda she e zamenen a ako ne to exit po gore she se vikne predi tozi tuk
  45. }
  46. else
  47. {
  48. waitpid(pid, 0, 0);
  49. }
  50. free(direction[0]); // napraktika freevame char *array = malloc(size * sizeof(char)); ot parse_cmdline
  51. free(direction);
  52.  
  53. if( feof(stdin) ) {break;}
  54. }
  55. free(suffer);
  56. return 0;
  57. }
  58.  
  59. char **parse_cmdline(const char *cmdline)
  60. {
  61. int size = strlen(cmdline);
  62. char *array = malloc(size * sizeof(char)); // trqq da e size + 1 shot strcpy slaga '\0' nakraq
  63. strcpy(array, cmdline);
  64.  
  65. int argc = 0;
  66. char **array_of_strings = malloc(sizeof(char*));
  67.  
  68. char *ptr = strtok(array, " ");
  69.  
  70. while (ptr)
  71. {
  72.  
  73.  
  74. array_of_strings[argc] = ptr;
  75.  
  76.  
  77. ptr = strtok(NULL, " ");
  78.  
  79. argc++;
  80. array_of_strings = realloc(array_of_strings, (argc+1) * sizeof(char*));// + 1 za posledniq element da e null
  81. }
  82. array_of_strings[argc] = NULL;// viz komentara po gore
  83.  
  84. return array_of_strings;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement