Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <unistd.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- #include <readline/readline.h>
- #include <readline/history.h>
- #include <sys/wait.h>
- #include <sys/types.h>
- int myshell_exit(char **args);
- int myshell_help(char **args);
- char **myshell_split_line(char *line);
- int myshell_execute(char **args);
- const int builtin_functions_total = 2;
- char *builtin_functions_names[] = { "help", "exit" };
- int (*builtin_functions[])(char **) = { &myshell_help, &myshell_exit };
- int myshell_exit(char **args)
- {
- exit(0);
- }
- int myshell_help(char **args)
- {
- printf("Built-in functions: help, exit\n");
- return 0;
- }
- char **myshell_split_line(char *line)
- {
- int bufsize = 64;
- int position = 0;
- char **tokens = malloc(bufsize * sizeof(char*));
- char *token;
- if(!tokens){
- fprintf(stderr, "myshell: allocation error\n");
- exit(EXIT_FAILURE);
- }
- token = strtok(line, " \t\r\n\a");
- while(token != NULL){
- tokens[position] = token;
- position++;
- if(position >= bufsize){
- bufsize += 64;
- tokens = realloc(tokens, bufsize * sizeof(char*));
- if(!tokens) {
- fprintf(stderr, "myshell: allocation error\n");
- exit(EXIT_FAILURE);
- }
- }
- token = strtok(NULL, " \t\r\n\a");
- }
- tokens[position] = NULL;
- return tokens;
- }
- int myshell_execute(char **args)
- {
- for(int i = 0; i < builtin_functions_total; i++){
- if(strcmp(args[0], builtin_functions_names[i]) == 0){
- return (*builtin_functions[i])(args);
- }
- }
- pid_t pid, wpid;
- int status;
- pid = fork();
- if(pid == 0){
- if(execvp(args[0], args) == -1){
- perror("myshell");
- }
- exit(EXIT_FAILURE);
- }else if (pid < 0){
- perror("myshell");
- }else{
- do{
- wpid = waitpid(pid, &status, WUNTRACED);
- } while(!WIFEXITED(status) && !WIFSIGNALED(status));
- }
- return 0;
- }
- int main(){
- int status = 0;
- char *line;
- char **args;
- do{
- line = readline("myshell> ");
- if(line){
- add_history(line);
- args = myshell_split_line(line);
- status = myshell_execute(args);
- free(line);
- free(args);
- }
- } while(status == 0);
- return status;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement