SHARE
TWEET

Untitled

a guest Oct 15th, 2019 67 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define  bfsize 100
  4.  
  5. int main(int argc, char **argv)
  6. {
  7.    shell();
  8.    
  9.     return 0;
  10. }
  11. void shell(void)
  12. {
  13.   char *command;
  14.   char **arguments;
  15.   int status;
  16.  
  17.   do {
  18.     printf("> ");
  19.     command = readcommand();
  20.     arguments = splitcommand(command);
  21.     status = shellexecution(arguments);
  22.  
  23.     free(command);
  24.     free(arguments);
  25.   } while (status);
  26. }
  27. char *readcommand(void)
  28. {
  29.   char *command = NULL;
  30.   size_t buffersize = 0;
  31.   getline(&command, &buffersize, stdin);
  32.   return command;
  33. }
  34. char **splitcommand(char *command)
  35. {
  36.   int buffersize = bfsize ;
  37.    i = 0;
  38.   char **tokens = malloc(buffersize * sizeof(char*));
  39.   char *token;
  40.  
  41.   if (!tokens) {
  42.     printf("An error occured \n");
  43.     exit(1);
  44.   }
  45.  
  46.   token = strtok(line, bfsize);
  47.   while (token != NULL) {
  48.     tokens[i] = token;
  49.     i++;
  50.  
  51.     if (i >= buffersize) {
  52.       buffersize = buffersize + bfsize;
  53.       tokens = realloc(tokens, buffersize * sizeof(char*));
  54.       if (!tokens) {
  55.         printf("An error occured\n");
  56.         exit(1);
  57.       }
  58.     }
  59.  
  60.     token = strtok(NULL, bfsize);
  61.   }
  62.   tokens[i] = NULL;
  63.   return tokens;
  64. }
  65. int shellexecution(char **args)
  66. {
  67.   pid_t pid;
  68.   pid_t wpid;
  69.   int status;
  70.  
  71.   pid = fork();
  72.   if (pid == 0) {
  73.     if (execvp(args[0], args) == -1) {
  74.       printf("An error occured \n");
  75.     }
  76.     exit(1);
  77.   } else if (pid < 0) {
  78.    printf("An error occured \n");
  79.   } else {
  80.     do {
  81.       wpid = waitpid(pid, &status, WUNTRACED);
  82.     } while (!WIFEXITED(status) && !WIFSIGNALED(status));
  83.   }
  84.  
  85.   return 1;
  86. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top