Advertisement
lamiastella

cd, cd sth, exit, everything works

Sep 25th, 2013
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.98 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <sys/wait.h>
  3. #include <unistd.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <sys/types.h>
  7. #include <assert.h>
  8. #include <signal.h>  //for kill
  9.  
  10. void execute(char **argv)
  11. {
  12.  
  13.   int status;
  14.   int pid = fork();
  15.   if (pid  <0)  //fork error has happened
  16.      {
  17.        perror("Can't fork a child process\n");
  18.        exit(EXIT_FAILURE);
  19.      }
  20.   if (pid==0)   //It's the child process and can run his task
  21.      {
  22.     execvp(argv[0],argv);
  23.         perror("error");  
  24.      }
  25.   else  //pid>0 it's the parent and should wait for the child
  26.      {
  27.         int status;
  28.        // int wc = wait(&status);
  29.        // assert(wc != -1);
  30.  
  31.       //while(wait(&status)!=pid)
  32.       //   ;
  33.         wait(NULL);  //the way taught in the class
  34.      }
  35.  
  36.  
  37. }
  38.  
  39. int main (int argc, char **argv)
  40.  
  41. {  char cwd[100];
  42.    char input[512];
  43.    char *args[512];
  44.    char **next = args;
  45.    char *temp;
  46.    getcwd(cwd,sizeof(cwd));
  47.    while (1)
  48.    {  
  49.       chdir(cwd);
  50.       printf("mysh> ");
  51.       fgets(input,512,stdin);
  52.       input[strlen(input) - 1] = 0;
  53.       temp = strtok(input, " ");
  54.       while(temp != NULL)
  55.              {
  56.                      //printf("%s\n", temp);
  57.                      *next++ = temp;
  58.                      temp = strtok(NULL, " ");
  59.                    
  60.               }      
  61.             *next = NULL;
  62.             next=args;
  63.        
  64.      if (strcmp(args[0], "exit")==0)
  65.             // exit(EXIT_SUCCESS);
  66.             exit(0);
  67.      if (strcmp(args[0], "cd")==0)
  68.           {
  69.            printf("argv[1] is  %s \n", args[1]);
  70.                if (!args[1])
  71.                  {
  72.                     chdir(getenv("HOME"));
  73.                     getcwd(cwd,sizeof(cwd));
  74.                  }
  75.                else
  76.                 {
  77.                    chdir(args[1]);
  78.                    getcwd(cwd,sizeof(cwd));
  79.                 }
  80.  
  81.  
  82.           }
  83.       else
  84.        {
  85.  
  86.         execute(args);
  87.       }
  88.      
  89.    }
  90.  
  91.    return 0;
  92.  
  93.  
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement