Advertisement
Guest User

Rado - Shell

a guest
Dec 15th, 2017
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.16 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <string.h>
  4. #include <stdlib.h>
  5. #include <sys/wait.h>
  6.  
  7. char **parse_cmdline( const char *cmdline ){
  8.     int command_count = 0;
  9.     char * pch;
  10.     char *copy = malloc(100);
  11.     strcpy(copy, cmdline);
  12.     pch = strtok(copy, " ");
  13.     char **commands = malloc(sizeof(char)*500);
  14.         while (pch != NULL){
  15.             commands[command_count++] = pch;
  16.             pch = strtok (NULL, " ,.-");
  17.         }
  18.         commands[command_count] = NULL;
  19.         return commands;
  20. }
  21.  
  22. int main(){
  23.     char *buffer = malloc(100);
  24.     int length = 0;
  25.     int processes = 0;
  26.     pid_t pid;
  27.     int c;
  28.     char **commands = malloc(sizeof(char)*500);
  29.     while ((c = getchar()) != EOF){
  30.         if(c == '\n'){
  31.             commands = parse_cmdline(buffer);
  32.             processes++;
  33.             pid = fork();
  34.             if(pid == 0){
  35.                 execv(commands[0] ,commands);
  36.             }
  37.             memset(buffer,0,strlen(buffer));
  38.             length = 0;
  39.         }
  40.         else buffer[length++] = c;
  41.     }
  42.     for(int i = 0; i < processes; i++){
  43.         wait(NULL);
  44.     }
  45.  
  46.     free(buffer);
  47.     return 0;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement