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()
- {
- size_t size=0; // razmera na prochetenoto
- char *suffer = NULL; // tuka she se zapishe tova koeto prochete getline
- while(1)
- {
- printf("$ ");
- ssize_t vladi = getline(&suffer,&size,stdin);//vrusta kolko e prochelo , - 1 pri EOF ili greshka
- if( feof(stdin) ) {break;}
- char** direction; //tuka pazim kakvoot vurne parse_cmdline
- suffer[strlen(suffer)-1]='\0'; /// mahame noviq red koito getline procheti sushto osven tova koeto e napisano
- direction = parse_cmdline(suffer);
- pid_t pid = fork(); // prvai nov proces
- if(pid < 0)
- {
- perror("fork");
- }
- else if(pid == 0)
- {
- int execv_result = execv(direction[0], direction);// ako se izpulni zamenq koda na procesa sus tozi na koito execvame
- if(execv_result == -1)// ako ima greshka ne zamenq koda
- {
- perror(direction[0]);
- free(direction[0]);
- free(direction);
- free(suffer);
- exit(0);
- }
- exit(0);//nenuzen exit tui kato ne moze da bude dostignat. ako exec proraboti to koda she e zamenen a ako ne to exit po gore she se vikne predi tozi tuk
- }
- else
- {
- waitpid(pid, 0, 0);
- }
- free(direction[0]); // napraktika freevame char *array = malloc(size * sizeof(char)); ot parse_cmdline
- free(direction);
- if( feof(stdin) ) {break;}
- }
- free(suffer);
- return 0;
- }
- char **parse_cmdline(const char *cmdline)
- {
- int size = strlen(cmdline);
- char *array = malloc(size * sizeof(char)); // trqq da e size + 1 shot strcpy slaga '\0' nakraq
- strcpy(array, cmdline);
- int argc = 0;
- char **array_of_strings = malloc(sizeof(char*));
- char *ptr = strtok(array, " ");
- while (ptr)
- {
- array_of_strings[argc] = ptr;
- ptr = strtok(NULL, " ");
- argc++;
- array_of_strings = realloc(array_of_strings, (argc+1) * sizeof(char*));// + 1 za posledniq element da e null
- }
- array_of_strings[argc] = NULL;// viz komentara po gore
- return array_of_strings;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement