Advertisement
Guest User

duplicate shell

a guest
May 23rd, 2018
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.85 KB | None | 0 0
  1. #include <time.h>
  2. #include <stdio.h>
  3. #include <unistd.h>
  4. #include <sys/wait.h>
  5. #include <string.h>
  6. #include <stdlib.h>
  7. #include <sys/types.h>
  8. #include <wordexp.h>
  9.  
  10.  
  11. void execute(char *user_input)
  12. {
  13.     pid_t pid;
  14.     //process gets assigned a 'lock' if you have the right key  it opens.
  15.     int state_loc;
  16.     if( (pid = fork()) == -1){
  17.       printf("fork failed\n");
  18.       exit(1);
  19.     }
  20.     else if(pid == 0){
  21.         FILE *f;
  22.         //open the file and append. Create if not there.
  23.         f = fopen("tmp.log", "a+");
  24.         if (f == NULL) { printf("Something is wrong");}
  25.  
  26.         struct tm *p;
  27.         struct tm buf;
  28.         char timestring[100];
  29.         time_t ltime = time(NULL);
  30.         if (NULL != (p=localtime_r(&ltime, &buf))){
  31.           strftime(timestring, sizeof(timestring),"** %c: ", p);
  32.           fprintf(f, "%s %s \n", timestring, user_input);
  33.         }
  34.         fclose(f);
  35.  
  36.         char* separator = " ";
  37.         char* argv[64];
  38.         int argc = 0;
  39.         char* tmp;
  40.         argv[argc] = strtok_r(user_input, separator, &tmp);
  41.         while( argv[argc] != NULL){
  42.           argc+=1;
  43.           argv[argc] = strtok_r(NULL, separator, &tmp);
  44.         }
  45.         // null termination array '\0'
  46.         argv[argc] = '\0';
  47.  
  48.       execvp(argv[0],argv);
  49.     }
  50.     else{
  51.       //waiting until the lock is open; imagine state_loc as if = 0, lock, else unlock
  52.       wait(&state_loc);
  53.     }
  54. }
  55.  
  56.  
  57. int main ()
  58. {
  59.   while(1)
  60.   {
  61.     char user_input[1024];
  62.     printf("recsh>> ");
  63.     //empty the buffer right scanf
  64.     scanf("%[^\n]", user_input);
  65.     //calls each character in the user input, repeat until it reaches the terminating \n
  66.     while( getchar() != '\n');
  67.     if(strcmp(user_input, "exit") == 0){
  68.       printf("Exiting\n");
  69.       break;
  70.     }
  71.     else{
  72.       execute(user_input);
  73.     }
  74.   }
  75.   return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement