Facebook
From Sloppy Water Vole, 3 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 83
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <signal.h>
  6. #include <stdbool.h>
  7. #include <time.h>
  8. #define MAX_STR 10
  9. #define MAX_CH 100
  10.  
  11.  
  12. void logFile(const char* str)
  13. {
  14.     time_t t = time(0);
  15.     /* open the file for writing*/
  16.     FILE *fp;
  17.     fp = fopen("log.txt", "w");
  18.     fprintf(fp, "%s %s\n",str,ctime(&t));
  19.     /* close the file*/
  20.     fclose (fp);
  21. }
  22.  
  23.  
  24. void read_line(char linechar[]) {
  25.     char* str = fgets(linechar,MAX_CH,stdin);
  26.  
  27.     int i=0;
  28.     while(linechar[i]!='\n'){       //remove \n from end of line
  29.         i++;
  30.     }
  31.     linechar[i] = '\0';
  32.  
  33.     if(str == NULL || strcmp(linechar,"exit") == 0){
  34.         exit(0);
  35.     }
  36. }
  37.  
  38.  
  39. bool line_parser(char* linestr[],char linechar[])
  40. {
  41.     int i = 0;
  42.     bool flag = false;
  43.     linestr[i]= strtok(linechar," ");
  44.     if(linestr[i] == NULL){
  45.         printf("NO COMMAND\n");
  46.     }
  47.     while(linestr[i] != NULL){
  48.         i++;
  49.         linestr[i]= strtok(NULL," ");
  50.     }
  51.  
  52.     if(i!=0 && strcmp(linestr[i-1] ,"&") == 0){      //check if the command includes "&" which means that the parent will no wait for child to finish
  53.         flag = true;
  54.         linestr[i - 1] = NULL;
  55.     }
  56.     return flag;
  57. }
  58.  
  59.  
  60. void SIGHandler(){
  61.     pid_t pid;
  62.     pid = wait(NULL);
  63.     if(pid>0) {
  64.         logFile("child process was terminated");;
  65.     }
  66. }
  67.  
  68.  
  69. bool line_Organizer(char* linestr[],char linechar[],bool flag){
  70.     printf("shell:~$ ");
  71.     read_line(linechar);
  72.     return line_parser(linestr,linechar);
  73. }
  74.  
  75.  
  76. int main()
  77. {
  78.     char* linestr[MAX_STR];
  79.     char linechar[MAX_CH];
  80.     bool flag;
  81.     while(1){
  82.         bool flag = line_Organizer(linestr,linechar,flag);
  83.         pid_t pid = fork();
  84.         signal(SIGCHLD,SIGHandler);
  85.         if (pid < 0) {
  86.             perror("Fork failed");
  87.             exit(1);
  88.         }
  89.         else if(pid == 0) {   //child
  90.             execvp(linestr[0],linestr);
  91.             if (execvp(linestr[0],linestr) < 0) {
  92.                 printf("ERROR: Invalid command\n");
  93.                 break;
  94.             }
  95.         } else {     //parent
  96.             if(flag) {
  97.                 flag = false;
  98.                 continue;
  99.             }
  100.             waitpid(pid,0);
  101.         }
  102.     }
  103.     return 0;
  104. }
  105.