Advertisement
Guest User

Untitled

a guest
Oct 16th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include<string.h>
  4. #include<unistd.h>
  5. #include<sys/types.h>
  6. #include<sys/wait.h>
  7. #include<signal.h>
  8. #define MAX 500 //Max Input
  9. #define ARGS 20 //Max number of arguments
  10. //handle the signal SIGCHLD when a child process is terminated
  11. void signalHandler(int sig_num)
  12. {
  13. FILE *fp;
  14. fp=fopen("shell_logfile.log","a+");// Open log file
  15. if(fp == NULL)
  16. {
  17. printf("\nerror:couldn't open file");
  18. }
  19. else fprintf(fp,"Child process was terminated\n");
  20. fclose(fp);
  21.  
  22. }
  23. void ExecuteBackground(char *parsedArguments[]){
  24. pid_t pid = fork();
  25. printf("\nDir 2");
  26. if(pid>=0){
  27. if(pid==0){
  28. execvp(parsedArguments[0],parsedArguments);
  29. }
  30. else {
  31. return;
  32. }
  33. }
  34. }
  35.  
  36.  
  37.  
  38. int Parse(char line[], char *parsedArguments[]) //Parsing
  39. {
  40. int i=0;
  41.  
  42. if((parsedArguments[i] = strtok(line," \n\t"))==NULL) return 0;
  43. i=1;
  44. //tokenize the input line by space
  45. while((parsedArguments[i] = strtok(NULL, " \n\t")) != NULL) i++;
  46. parsedArguments[i]= NULL;
  47. return i;
  48. }
  49. int ExecuteProcess(char *parsedArguments[]){
  50. pid_t pid = fork();
  51. if(pid==-1){
  52. printf("\nFailed Fork");
  53. return ;
  54. }
  55. else if(pid==0) {
  56. if(execvp(parsedArguments[0],parsedArguments)<0){
  57. printf("Could not Execute Command");
  58. }
  59. exit(0);
  60. }
  61. else{
  62. wait(NULL);
  63. }
  64. }
  65. int main()
  66. {
  67. char line[MAX]; // User Input
  68. char *parsedArgument[ARGS]; // Arguments in Command (tokens)
  69. int count=0;
  70. int status;
  71. int flag=1;
  72. struct sigaction sa;
  73.  
  74. sa.sa_handler = signalHandler; // to call my signal handling functions
  75. sigemptyset(&sa.sa_mask); //set sa with zeros
  76. sigaction(SIGCHLD,&sa,NULL);
  77. printf("Simple Shell");
  78. while(1)
  79. {
  80. printf("\n>>>");
  81. fgets(line, MAX, stdin);//Read Input from User
  82. count=Parse(line,parsedArgument);//Parsing Input
  83. if(count==0){
  84. continue;
  85. }
  86. if(strcmp(parsedArgument[0],"exit") == 0)
  87. {
  88. exit(0);
  89. }
  90. if(strcmp(parsedArgument[count-1],"&")==0){
  91. flag=2;
  92. parsedArgument[count-1]='\0';
  93. count--;
  94. }
  95.  
  96. if(flag==1){
  97. ExecuteProcess(parsedArgument);
  98. }
  99. else{
  100. ExecuteBackground(parsedArgument);
  101. }
  102. }
  103.  
  104. return 0;
  105. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement