/* * Rick van der Zwet * 0433373 * OS Assigment 1 - Part B * Licence: BSD * $Id: simple-shell.c 487 2008-02-20 12:51:08Z rick $ */ #include #include #include #include int main (int argc, char * argv[]) { char **ap; /* Argument list pointer */ char *argv_c[256]; /* argument input list */ char *bp; /* Buffer pointer */ char *commandsep = " \t"; /* Command seperation characters */ char *pathsep = ":"; /* Path seperation character */ char *pathv[256]; /* path list */ char fullpath[1024] = ""; /* fullpath to binary */ char inbuf[256]; /* input buffer */ int argc_c; /* Argument list lengh */ int i; /* tmp loop counter */ int pathc = 0; /* path list lengh */ /* Input argument viewer */ printf("Number of arguments %i\n", argc); for (i = 0; i < argc; i++) { printf("Command line argument %i: %s\n", i, argv[i]); } /* put ENV:PATH into path list */ printf("Env PATH=%s\n", getenv("PATH")); bp = getenv("PATH"); for (ap = pathv; (*ap = strsep(&bp, pathsep)) != NULL;) { pathc++; if (**ap != '\0') if (++ap >= &pathv[256]) break; } /* Main shell */ for (;;) { /* Get input */ printf("$ "); fgets(inbuf, 256, stdin); inbuf[strlen(inbuf) - 1] = '\0'; /* Convert input to arguments */ bp = inbuf; argc_c = 0; for (ap = argv_c; (*ap = strsep(&bp, commandsep)) != NULL;) { printf("Argument %i : '%s'\n",argc_c, argv_c[argc_c]); argc_c++; if (**ap != '\0') if (++ap >= &argv_c[256]) break; } /* Catch special cases */ if ( argv_c[0] == '\0' ) { printf("No input...\n"); continue; } if (strcmp(argv_c[0], "exit") == 0) { printf("Goodbye...\n"); break; } /* Find proper executable in path */ for (i = 0; i < pathc; i++) { (void)strcpy(fullpath, pathv[i]); (void)strcat(fullpath, "/"); (void)strcat(fullpath, argv_c[0]); printf("Searching at '%s': ", fullpath); if (access(fullpath, X_OK) == 0) { printf("OK\n"); /* Execute command, using fork */ int pid = fork(); if (pid > 0) { wait(NULL); break; } else { printf("Executing: %s ", fullpath); for (i = 1; i < argc_c; i++) { printf("%s ",argv_c[i]); } printf("\n"); execv(fullpath, argv_c); } } else { printf("FAILED\n"); } } } return(0); }