Advertisement
Guest User

Untitled

a guest
Jan 17th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/wait.h>
  5. #include <string.h>
  6.  
  7. typedef struct {
  8. char *prog;
  9. char **args;
  10. } command;
  11.  
  12. command parseInput(char* input);
  13.  
  14. int main(int argc, char *argv[])
  15. {
  16.  
  17. while (1) {
  18.  
  19. char input[512]; //store input line
  20. printf("$sshell "); //shell prompt
  21. fgets(input, 512, stdin); //read line into string
  22. input[strlen(input) - 1] = '\0';
  23.  
  24.  
  25.  
  26. //check for exit command
  27. if (strcmp(input, "exit") == 0) {
  28.  
  29. exit(0);
  30.  
  31. } else {
  32.  
  33. //create new process
  34. pid_t PID = fork();
  35.  
  36. //if child process
  37. if (PID == 0) {
  38.  
  39. int status;
  40. command comm = parseInput(input);
  41. status = execvp(comm.prog, comm.args);
  42.  
  43. //if exec fails
  44. if (status != 0) {
  45.  
  46. fprintf(stderr, "Error: command not found.\n");
  47. exit(42);
  48.  
  49. //else exit the process
  50. } else {
  51.  
  52. exit(0);
  53.  
  54. }
  55.  
  56. } else {
  57.  
  58. int status;
  59. wait(&status);
  60. fprintf(stderr, "+ completed '%s' [%d]\n", input, WEXITSTATUS(status));
  61.  
  62. }
  63. }
  64. }
  65. return EXIT_SUCCESS;
  66. }
  67.  
  68. command parseInput(char *input) {
  69.  
  70. command comm;
  71. int i = 1;
  72. char *token;
  73.  
  74. token = strtok(input, " ");
  75. //printf("Got a token: %s\n", token);
  76.  
  77. comm.prog = (char*) malloc(strlen(token) + 1);
  78. strcpy(comm.prog, token);
  79.  
  80. comm.args = (char**) malloc(sizeof(char*) * 50);
  81.  
  82. comm.args[0] = (char*) malloc(strlen(token) + 1);
  83. strcpy(comm.args[0], token);
  84.  
  85. while(1) {
  86. token = strtok(NULL, " \n");
  87.  
  88. if (token == NULL) {
  89. break;
  90. }
  91.  
  92. comm.args[i] = (char*) malloc(strlen(token) + 1);
  93. strcpy(comm.args[i], token);
  94. }
  95. comm.args[i + 1] = (char*) malloc(sizeof((char*) NULL));
  96. comm.args[i + 1] = (char*) NULL;
  97.  
  98. return comm;
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement