Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/wait.h>
- char **parse_cmdline(const char *cmdline);
- int main()
- {
- int i;
- while(1)
- {
- printf("$ ");
- char** direction;
- size_t size=0;
- char *suffer = NULL;
- ssize_t vladi = getline(&suffer,&size,stdin);
- if( feof(stdin) ) {break;}
- suffer[strlen(suffer)-1]=' ';
- direction = parse_cmdline(suffer);
- printf("%s",direction[2]);
- free(suffer);
- pid_t pid = fork();
- if(pid < 0)
- {
- perror("fork");
- }
- else if(pid == 0)
- {
- int execv_result = execv(direction[0], direction);
- if(execv_result == -1)
- {
- perror(direction[0]);
- free(direction[0]);
- free(direction);
- exit(0);
- }
- exit(0);
- }
- else
- {
- waitpid(pid, 0, 0);
- }
- free(direction[0]);
- free(direction);
- }
- return 0;
- }
- char **parse_cmdline(const char *cmdline)
- {
- int size = strlen(cmdline);
- char *array = malloc(size * sizeof(char));
- strcpy(array, cmdline);
- int argc = 0;
- char **array_of_strings = malloc(sizeof(char*));
- char *ptr = strtok(array, " ");
- while (ptr)
- {
- array_of_strings = realloc(array_of_strings, (argc+1) * sizeof(char*));
- array_of_strings[argc] = ptr;
- ptr = strtok(NULL, " ");
- argc++;
- }
- array_of_strings[argc] = NULL;
- return array_of_strings;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement