Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<sys/wait.h>
- #include<unistd.h>
- #include<stdlib.h>
- #include<string.h>
- #define READLINE_BUFFER 1024
- #define BUFSIZE 64
- #define DELIMITER " \t\r\n\a"
- char* buffer = NULL;
- int startFunc(char **args){
- pid_t pid, wpid;
- int process_status;
- pid = fork();
- if(pid == 0){
- //Child process
- if(execvp(args[0], args) < 0){
- perror(args[0]);
- free(args);
- free(buffer);
- buffer = NULL;
- exit(1);
- }
- } else if(pid < 0){
- //Error forking
- perror("fork");
- } else{
- //Parent process
- waitpid(pid, &process_status, 0);
- }
- return 1;
- }
- int executeFunc(char **args){
- if(args[0] == NULL){
- return 1; //An empty command was entered
- }
- return startFunc(args);
- }
- char *readLine(){
- int bufsize = READLINE_BUFFER;
- int position = 0;
- buffer = malloc(sizeof(char) * bufsize);
- int c;
- if(!buffer){
- fprintf(stderr, "No such file or directory\n");
- exit(EXIT_FAILURE); // an unsuccessfull termination status is returned to the host env
- }
- while(1){
- //reads character
- c = getchar();
- if(c == EOF){
- free(buffer);
- buffer = NULL;
- exit(0);
- }
- if(c == '\n'){
- buffer[position] = '\0';
- return buffer;
- } else{
- buffer[position] = c;
- }
- position++;
- if(position >= bufsize){
- bufsize += READLINE_BUFFER;
- buffer = realloc(buffer, bufsize);
- if(!buffer){
- fprintf(stderr, "No such file or directory");
- exit(EXIT_FAILURE); // an unsuccessfull termination status is returned to the host env
- }
- }
- }
- }
- char **parse_cmdline(const char *line){
- int bufsize = BUFSIZE, pos = 0;
- char **tokens = malloc(bufsize * sizeof(char*));
- char *token;
- if(!tokens){
- fprintf(stderr, "No such file or directory\n");
- exit(EXIT_FAILURE); // an unsuccessfull termination status is returned to the host env
- }
- token = strtok((char*)line, DELIMITER); //breaks string str into a series of tokens using the delimiter delim.
- while(token != NULL){
- tokens[pos] = token;
- pos++;
- if(pos >= bufsize){
- bufsize += BUFSIZE;
- tokens = realloc(tokens, bufsize * sizeof(char*));
- if(!tokens){
- fprintf(stderr, "Permission denied");
- }
- }
- token = strtok(NULL , DELIMITER);
- }
- tokens[pos] = NULL;
- return tokens;
- }
- void Cyclecommands(){
- int tmpexe;
- char *cmdline;
- char **arg;
- while(tmpexe){
- write(0, "$ ", 2);
- cmdline = readLine();
- arg = parse_cmdline(cmdline);
- tmpexe = executeFunc(arg);
- free(cmdline);
- free(arg);
- buffer = NULL;
- }
- }
- int main(int argc, char **argv){
- Cyclecommands();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement