Advertisement
Guest User

Untitled

a guest
Oct 16th, 2019
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 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. if(pid>=0){
  26. if(pid==0){
  27. execvp(parsedArguments[0],parsedArguments);
  28. }
  29. else {
  30. printf("Error Parsing");
  31. }
  32. }
  33. }
  34.  
  35.  
  36.  
  37. int Parse(char line[], char *parsedArguments[]) //Parsing
  38. {
  39. int i=0;
  40.  
  41. if((parsedArguments[i] = strtok(line," \n\t"))==NULL) return 0;
  42. i=1;
  43. //tokenize the input line by space
  44. while((parsedArguments[i] = strtok(NULL, " \n\t")) != NULL) i++;
  45. parsedArguments[i]= NULL;
  46. return i;
  47. }
  48. int ExecuteProcess(char *parsedArguments[]){
  49. pid_t pid = fork();
  50. if(pid==-1){
  51. printf("\nFailed Fork");
  52. return ;
  53. }
  54. else if(pid==0) {
  55. if(execvp(parsedArguments[0],parsedArguments)<0){
  56. printf("Could not Execute Command");
  57. }
  58. exit(0);
  59. }
  60. else{
  61. wait(NULL);
  62. }
  63. }
  64. int main()
  65. {
  66. char line[MAX]; // User Input
  67. char *parsedArgument[ARGS]; // Arguments in Command (tokens)
  68. int count=0;
  69. int status;
  70. int flag=1;
  71. struct sigaction sa;
  72.  
  73. sa.sa_handler = signalHandler; // to call my signal handling functions
  74. sigemptyset(&sa.sa_mask); //set sa with zeros
  75. sigaction(SIGCHLD,&sa,NULL);
  76. printf("Simple Shell");
  77. while(1)
  78. {
  79. printf("\n>>>");
  80. fgets(line, MAX, stdin);//Read Input from User
  81. count=Parse(line,parsedArgument);//Parsing Input
  82. if(count==0){
  83. continue;
  84. }
  85. if(strcmp(parsedArgument[0],"exit") == 0)
  86. {
  87. exit(0);
  88. }
  89. if(strcmp(parsedArgument[count-1],"&")==0){
  90. flag=2;
  91. }
  92.  
  93. if(flag==1){
  94. ExecuteProcess(parsedArgument);
  95. }
  96. else{
  97. ExecuteBackground(parsedArgument);
  98. }
  99. }
  100.  
  101. return 0;
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement