Advertisement
Guest User

Untitled

a guest
Feb 14th, 2016
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.44 KB | None | 0 0
  1.  
  2. // Milestone 1
  3.  
  4.  
  5. int main(int argc, char *argv[])
  6. {
  7. char comm[100];
  8. printf("Introduceti comanda:");
  9. comm=scanf("%s", comm);
  10.  
  11. if(strcmp(comm, "exit"))
  12. {
  13. printf("Exit");
  14. }
  15.  
  16.  
  17. return EXIT_SUCCESS;
  18. }
  19.  
  20.  
  21.  
  22.  
  23.  
  24.  
  25.  
  26.  
  27.  
  28. // Milestone 2
  29.  
  30.  
  31. #include <stdio.h>
  32. #include <sys/types.h>
  33. #include <sys/stat.h>
  34. #include <stdlib.h>
  35. #include<fcntl.h>
  36. #include <unistd.h>
  37. #define BUFFER_SIZE 256
  38. #define READFILE_SIZE 4096
  39.  
  40. char ** parseCMD( char * );
  41. void EXEC(char *, char *);
  42.  
  43. int main(int argc, char * argv[])
  44. {
  45. char myPrompt[]= {'>', '_', '\0'};
  46. char *currLine = (char* ) malloc(sizeof(char) * BUFFER_SIZE),
  47. *command = (char* ) malloc(sizeof(char) * BUFFER_SIZE),
  48. *argument = (char* ) malloc(sizeof(char) * BUFFER_SIZE);
  49.  
  50. scanf("%c", currLine);
  51. while((strcmp(currLine, "exit") != 0))
  52. {
  53. command = strtok(currLine, " ");
  54. argument = strtok( NULL, "");
  55. EXEC(command, argument);
  56. currLine = myPrompt;
  57. }
  58. return 0;
  59. }
  60.  
  61. char ** parseCMD( char * buff )
  62. {
  63. int i = 0, n = strlen(buff), j, count = 0;
  64. char ** CMDargs = (char **) malloc( sizeof( char ) * 100 * 100);
  65. if( buff == NULL )
  66. return NULL;
  67. for(i; i < n; i ++)
  68. {
  69. j = 0;
  70. char * aux = (char *) malloc( sizeof( char ) * 100);
  71. while( buff[i] != ' ' || buff[i] != '\t' || buff[i] != '\n')
  72. aux[j++] = buff[i++];
  73. aux[j] = '\0';
  74. CMDargs[count] = strdup( aux );
  75. count++;
  76. //printf("Argument %d is: %s", count - 1, CMDargs[count - 1]);
  77. free(aux);
  78. }
  79. CMDargs[ count ] = NULL;
  80. return CMDargs;
  81. }
  82.  
  83. void EXEC(char *command, char *argBuffer)
  84. {
  85. pid_t pid;
  86. int status, fd[2], n;
  87. char s[255];
  88. char ** Args;
  89. pipe( fd );
  90. Args = parseCMD( argBuffer );
  91. if ((pid = fork()) < 0)
  92. {
  93. printf("ERROR: forking child process failed\n");
  94. exit(1);
  95. }
  96. else if (pid == 0)
  97. {
  98. close(fd[0]);
  99. dup2(fd[1],1);
  100. if (execvp(command, Args) < 0)
  101. {
  102. printf("ERROR: execvp call failed\n");
  103. exit(1);
  104. }
  105. close(fd[1]);
  106. }
  107. else
  108. {
  109. close(fd[1]);
  110. while( ( n = read( fd[0], s, 255 ) ) > 0 )
  111. {
  112. s[n] = '\0';
  113. printf("%s",s);
  114.  
  115. }
  116. while (wait(&status) != pid);
  117. close(fd[0]);
  118. }
  119. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement