Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <signal.h>
  5. #include <unistd.h>
  6. #include <sys/types.h>
  7. #include <sys/wait.h>
  8.  
  9. pid_t global_pid;
  10.  
  11. void handler(int sig) {
  12. pid_t pid=wait(NULL);
  13.  
  14. if(pid==-1) {
  15. return;
  16. }
  17. FILE *fp;
  18.  
  19. fp = fopen("trace.log", "a+");
  20. fprintf(fp,"Executed successfully %d\n",pid);
  21. fclose(fp);
  22. }
  23.  
  24. int main() {
  25. printf(">>>>>> S I M P L E S H E L L <<<<<<\n");
  26. char command[100];
  27. char * ptr;
  28. char* token;
  29. char * args[100];
  30. while(1) {
  31. printf("Enter your command: ");
  32. //scan command
  33. gets(command);
  34. if(!strlen(command)) {
  35. printf("No input found! -- ");
  36. continue;
  37. }
  38. //skip white spaces
  39. int end=strlen(command)-1;
  40.  
  41. while(command[end]==' ') {
  42. end--;
  43. if(end==0)
  44. break;
  45. }
  46.  
  47.  
  48.  
  49. //check if the last char is & or not
  50. int dontwait=(int) command[end]=='&' ;
  51. if(dontwait == 1) {
  52. command[end]='\0';
  53. }
  54.  
  55. //if(dontwait)printf("Found & don't wait\n");
  56. //else printf("Wait\n");
  57.  
  58.  
  59.  
  60. //generate args list
  61. int i=0;
  62.  
  63. token= strtok(command," ");
  64.  
  65.  
  66. while (token != NULL) {
  67. args[i++]=token;
  68. token = strtok(NULL, " ");
  69. }
  70. //i-=(int)dontwait==1;
  71. args[i]=NULL;
  72.  
  73. //execute
  74. if(!strcmp(args[0],"exit")) {
  75. exit(0);
  76. } else if (!strcmp(args[0],"cd")) {
  77. chdir(args[1]);
  78. } else {
  79.  
  80.  
  81. pid_t pid=fork();
  82.  
  83. if(pid==0) { //child
  84. if(-1 == execvp(args[0],args)) {
  85. printf("Invalid commadn.\n");
  86. }
  87. exit(0);
  88. } else { //parent
  89.  
  90. if(!dontwait) {
  91. wait(NULL);
  92. FILE *fp;
  93.  
  94. fp = fopen("trace.log", "a+");
  95. fprintf(fp,"Executed successfully %d\n",pid);
  96. fclose(fp);
  97. } else {
  98. signal(SIGCHLD,handler);
  99. }
  100.  
  101. }
  102. }
  103.  
  104. }
  105. return 0;
  106. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement