Advertisement
Guest User

Untitled

a guest
May 27th, 2015
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. #include <unistd.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5.  
  6. #include <readline/readline.h>
  7. #include <readline/history.h>
  8. #include <sys/wait.h>
  9. #include <sys/types.h>
  10.  
  11. int myshell_exit(char **args);
  12. int myshell_help(char **args);
  13. char **myshell_split_line(char *line);
  14. int myshell_execute(char **args);
  15.  
  16. const int builtin_functions_total = 2;
  17. char *builtin_functions_names[] = { "help", "exit" };
  18. int (*builtin_functions[])(char **) = { &myshell_help, &myshell_exit };
  19.  
  20. int myshell_exit(char **args)
  21. {
  22. exit(0);
  23. }
  24.  
  25. int myshell_help(char **args)
  26. {
  27. printf("Built-in functions: help, exit\n");
  28. return 0;
  29. }
  30.  
  31. char **myshell_split_line(char *line)
  32. {
  33. int bufsize = 64;
  34. int position = 0;
  35. char **tokens = malloc(bufsize * sizeof(char*));
  36. char *token;
  37.  
  38. if(!tokens){
  39. fprintf(stderr, "myshell: allocation error\n");
  40. exit(EXIT_FAILURE);
  41. }
  42.  
  43. token = strtok(line, " \t\r\n\a");
  44.  
  45. while(token != NULL){
  46. tokens[position] = token;
  47. position++;
  48.  
  49. if(position >= bufsize){
  50. bufsize += 64;
  51. tokens = realloc(tokens, bufsize * sizeof(char*));
  52. if(!tokens) {
  53. fprintf(stderr, "myshell: allocation error\n");
  54. exit(EXIT_FAILURE);
  55. }
  56. }
  57. token = strtok(NULL, " \t\r\n\a");
  58. }
  59.  
  60. tokens[position] = NULL;
  61. return tokens;
  62. }
  63.  
  64. int myshell_execute(char **args)
  65. {
  66. for(int i = 0; i < builtin_functions_total; i++){
  67. if(strcmp(args[0], builtin_functions_names[i]) == 0){
  68. return (*builtin_functions[i])(args);
  69. }
  70. }
  71.  
  72. pid_t pid, wpid;
  73. int status;
  74.  
  75. pid = fork();
  76.  
  77. if(pid == 0){
  78. if(execvp(args[0], args) == -1){
  79. perror("myshell");
  80. }
  81. exit(EXIT_FAILURE);
  82. }else if (pid < 0){
  83. perror("myshell");
  84. }else{
  85. do{
  86. wpid = waitpid(pid, &status, WUNTRACED);
  87. } while(!WIFEXITED(status) && !WIFSIGNALED(status));
  88. }
  89.  
  90. return 0;
  91. }
  92.  
  93. int main(){
  94. int status = 0;
  95. char *line;
  96. char **args;
  97.  
  98. do{
  99. line = readline("myshell> ");
  100.  
  101. if(line){
  102. add_history(line);
  103. args = myshell_split_line(line);
  104. status = myshell_execute(args);
  105.  
  106. free(line);
  107. free(args);
  108. }
  109.  
  110. } while(status == 0);
  111.  
  112. return status;
  113. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement