Advertisement
agudelo1200

super simple shell

Apr 6th, 2020
277
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.37 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <string.h>
  5. #include <sys/wait.h>
  6.  
  7.  
  8. /**
  9.  * exe - execute the cmd
  10.  * @str: string that contains the cmd
  11.  */
  12. void exe(char str[])
  13. {
  14.     char *cmd;
  15.     const char del[] = " \t\r\n\v\f";
  16.     char *token;
  17.  
  18.     cmd = strdup(str);
  19.  
  20.     /* get the first token */
  21.     token = strtok(cmd, del);
  22.  
  23.     if (token != NULL)
  24.     {
  25.         char *av[] = {token, NULL}; /* set av[0] in the token */
  26.  
  27.             if (execve(av[0], av, NULL) == -1)
  28.             {
  29.                 perror("Error");
  30.             }
  31.     }
  32. }
  33.  
  34. /**
  35.  * main - a super simple shell that can run commands with their full path,
  36.  *        without any argument.
  37.  *
  38.  * Return: 0 success
  39.  */
  40.  
  41. int main(void)
  42. {
  43.     size_t size = 100;
  44.     char *cmd;
  45.  
  46.     /*system("clear");  clear screen */
  47.     printf("press Ctrl + D to exit\n");
  48.  
  49.     while (1) /* allows the loop to run indefinitely */
  50.     {
  51.         cmd = (char *)malloc(size * sizeof(cmd)); /* set memory space for cmd */
  52.         if (cmd == NULL)
  53.         {
  54.             exit(-1);
  55.         }
  56.  
  57.         printf("SHELL >> ");
  58.  
  59.         /* if it throws error, it frees memory and ends */
  60.         if (getline(&cmd, &size, stdin) == -1)/* get command entered in console */
  61.         {
  62.             free(cmd);
  63.             putchar(10);
  64.             exit(-1);
  65.         }
  66.  
  67.         /* create the child process and send the command to execute */
  68.         pid_t pid = fork();
  69.  
  70.         if (!pid)
  71.         {
  72.             exe(cmd);
  73.             break;
  74.         }
  75.         else
  76.             wait(NULL);
  77.         free(cmd);
  78.     }
  79.     return (0);
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement