Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <string.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/types.h>
- #define MAXLINE 81
- #define MAXARG 10
- #define WHITE "\t \n"
- #define RED "\x1B[31m"
- #define GRN "\x1B[32m"
- #define RESET "\x1B[0m"
- void execCommand(char *input){
- char *args[MAXARG]; //array of tokens
- char *token;
- int tknCtr = 0;
- /*Split string into tokens*/
- //first token
- token = strtok(input, WHITE);
- args[0] = token;
- //all other tokens
- while(token != NULL){
- token = strtok(NULL, WHITE);
- args[++tknCtr] = token;
- }
- /*Shell fork*/
- int forkStatus = 0;
- pid_t pexec, waitPexec;
- if ((pexec = fork()) == 0){
- //search current directory, including relative paths
- int status = execv(args[0], args);
- //search /bin directory
- if( status == -1){
- //prepend first token with /bin directory
- char dir1[80] = "/bin";
- char buf[256];
- snprintf(buf, sizeof buf, "%s/%s", dir1, args[0]);
- args[0] = buf;
- status = execv(args[0], args);
- //binary not found in /bin directory
- if( status == -1){
- printf(RED"\n\t/!\\ ERROR: command not found/!\\\n\n"RESET);
- }
- }
- exit(0);
- } else if (pexec < 0) {
- printf(RED"\n\t/!\\ ERROR: could not fork executor /!\\\n"RESET);
- } else {
- while ((waitPexec = wait(&forkStatus)) > 0); //wait on child
- }
- }
- int main(){
- char input[MAXLINE];
- do{
- printf(GRN"What command do you desire: "RESET);
- scanf("%80[^\n]", input); //read until enter pressed
- while ((getchar()) != '\n'); //flush stdin buffer
- if (strcmp(input, "exit") == 0) break;
- execCommand(input);
- } while (strcmp(input, "exit") != 0);
- printf("\n\tGOODBYE !\n");
- exit(EXIT_SUCCESS);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement