Advertisement
Guest User

Untitled

a guest
Jan 16th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 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. void doStuff(char *input);
  8.  
  9. struct COMMAND {
  10. char *prog;
  11. char **args;
  12. };
  13.  
  14. int main(int argc, char *argv[])
  15. {
  16. char *path = "/bin/";
  17.  
  18. while (1) {
  19.  
  20. char input[512];
  21. printf("$sshell ");
  22.  
  23. scanf("%s", input);
  24.  
  25. if (strcmp(input, "exit") == 0) {
  26. exit(0);
  27. } else {
  28. doStuff(input);
  29. exit(7);
  30. }
  31. }
  32. return EXIT_SUCCESS;
  33. }
  34.  
  35. void doStuff(char *input) {
  36.  
  37. COMMAND comm;
  38. char *temp = strtok(input, " ");
  39. char *arg = strtok(NULL, " ");
  40. comm.args = NULL;
  41.  
  42. int count = 0;
  43. comm.args = (char**)realloc(comm.args, (count + 1) * sizeof(*comm.args));
  44. comm.args[0] = (char*)malloc(sizeof(temp));
  45. strcpy(comm.args[count], temp);
  46. count++;
  47.  
  48. while (arg != NULL) {
  49. comm.args = (char**)realloc(comm.args, (count + 1) * sizeof(*comm.args));
  50. comm.args[count] = (char*)malloc(sizeof(arg));
  51. strcpy(comm.args[count], arg);
  52. count++;
  53. arg = strtok(NULL, " ");
  54. }
  55.  
  56. comm.args = (char**)realloc(comm.args, (count + 1) * sizeof(*comm.args));
  57. comm.args[count] = (char*)malloc(sizeof(NULL));
  58. comm.args[count] = NULL;
  59.  
  60. comm.prog = malloc(strlen(path) + strlen(temp) + 1);
  61.  
  62. if (comm.prog == NULL) {
  63. printf("Malloc failed.\n");
  64. exit(69);
  65. }
  66.  
  67. strcat(comm.prog, path);
  68. strcat(comm.prog, input);
  69. printf("%s\n", comm.prog);
  70.  
  71.  
  72. pid_t PID = fork();
  73.  
  74.  
  75. if (PID == 0) {
  76. int status;
  77. status = execvp(comm.prog, comm.args);
  78. if (status != 0) {
  79. fprintf(stderr, "Error: command not found.\n");
  80. exit(42);
  81. }
  82. else {
  83. exit(0);
  84. }
  85. }
  86. else {
  87. int status;
  88. wait(&status);
  89. fprintf(stderr, "+ completed '%s %s' [%d]\n", path, comm.args[1], WEXITSTATUS(status));
  90. }
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement