Advertisement
axyd

myshell_dynamic_array_Size

Jun 12th, 2024
435
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.69 KB | None | 0 0
  1. #include <string.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. #include <sys/types.h>
  6.  
  7. #define MAXLINE 81
  8. #define MAXARG 10
  9. #define WHITE "\t \n"
  10. #define RED   "\x1B[31m"
  11. #define GRN   "\x1B[32m"
  12. #define RESET "\x1B[0m"
  13.  
  14. void execCommand(char *input){
  15.     char *args[MAXARG]; //array of tokens
  16.     char *token;
  17.     int tknCtr = 0;
  18.  
  19.     /*Split string into tokens*/
  20.     //first token
  21.     token = strtok(input, WHITE);
  22.     args[0] = token;
  23.     //all other tokens
  24.     while(token != NULL){
  25.         token = strtok(NULL, WHITE);
  26.         args[++tknCtr] = token;
  27.     }
  28.    
  29.     /*Shell fork*/
  30.     int forkStatus = 0;
  31.     pid_t pexec, waitPexec;
  32.  
  33.     if ((pexec = fork()) == 0){
  34.         //search current directory, including relative paths
  35.         int status = execv(args[0], args);
  36.  
  37.         //search /bin directory
  38.         if( status == -1){
  39.             //prepend first token with /bin directory
  40.             char dir1[80] = "/bin";
  41.             char buf[256];
  42.  
  43.             snprintf(buf, sizeof buf, "%s/%s", dir1, args[0]);
  44.             args[0] = buf;
  45.  
  46.             status = execv(args[0], args);
  47.            
  48.             //binary not found in /bin directory
  49.             if( status == -1){
  50.                 printf(RED"\n\t/!\\ ERROR: command not found/!\\\n\n"RESET);
  51.             }
  52.         }
  53.         exit(0);
  54.     } else if (pexec < 0) {
  55.         printf(RED"\n\t/!\\ ERROR: could not fork executor /!\\\n"RESET);
  56.     } else {
  57.         while ((waitPexec = wait(&forkStatus)) > 0);    //wait on child
  58.     }
  59. }
  60.  
  61. int main(){
  62.     char input[MAXLINE];
  63.    
  64.     do{
  65.         printf(GRN"What command do you desire: "RESET);
  66.    
  67.         scanf("%80[^\n]", input);       //read until enter pressed     
  68.         while ((getchar()) != '\n');    //flush stdin buffer
  69.  
  70.         if (strcmp(input, "exit") == 0) break;
  71.  
  72.         execCommand(input);
  73.     } while (strcmp(input, "exit") != 0);
  74.    
  75.     printf("\n\tGOODBYE !\n");
  76.     exit(EXIT_SUCCESS);
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement