#include "./stdinc.h" // // Purpose: Homework 3, Problem 6 // Usage: t_exec [-v] [-d] < Command // -v verbose mode // -d debug mode (output some details) // (not part of the assignment) // --| constants |-- const int MAX_LINE = 50; const int BUFSZ = 100; const char *WHITE = " \t\n"; // white space characters // --| prototypes |-- void eval(char *word[]); void getArgs(int argc, char *argv[]); int getTokens(char *cmnd, char *word[], const char *delim); // --| globals |-- int verbose = 0; int debug = 0; // --| in-line functions |-- static inline // display prompt and get command char * getcmnd(char *cmnd) { char * s; printf("> "); s = fgets(cmnd, MAX_LINE, stdin); if (cmnd[strlen(cmnd)-1] != '\n') { fprintf(stderr, "*** Ooops, line too long\n"); exit(1); } printf("%s", cmnd); fflush(stdout); return s; } int main (int argc, char *argv[]) { char cmnd[MAX_LINE]; // command-line char *word[BUFSZ]; // word[k] points to kth word int nwords; // #words in command line int i; getArgs(argc, argv); while (getcmnd(cmnd) != NULL) { nwords = getTokens(cmnd, word, WHITE); if (strcmp(word[0], "quit") == 0) break; eval(word); } return 0; } void getArgs(int argc, char *argv[]) { int c; int ok = 1; while ((c = getopt(argc, argv, "dv")) != -1) { switch(c) { case 'd': debug = 1; break; case 'v': verbose = 1; break; default: ok = 0; DEBUG( (stderr, "getArgs: Unknown flag %c\n", c) ); break; } } if (!ok) { fprintf(stderr, "Usage: t_exec [-v] [-d] < Command\n"); exit(1); } } // --| get tokens |-- // Semantics: (nwords, word[]) = getTokens(cmnd,delim) // where cmnd is the command line // delim is the deliminator string // nwords is number of words in command line // word[] is array of ptrs to words in command line // Usage: int nwords = getTokens(cmnd, word, " \t\n"); // where char cmnd[]; // char *word[]; int getTokens(char *cmnd, char *word[], const char *delim) { int nwords = 0; char *p = cmnd; char *token; while ((token=strtok(p,delim)) != NULL) { word[nwords] = token; DEBUG( (stderr, "\tword[%d] = %s\n", nwords, token) ); nwords++; p = NULL; } word[nwords] = NULL; return nwords; } // --| evaluate a command |-- void eval(char *word[]) { pid_t pid; int status; struct timeval tv1, tv2; double t; // elapsed time in msec gettimeofday(&tv1, 0); if ( (pid = Fork()) == 0) { // child if (verbose) { int i = 0; fprintf(stderr, "\tverbose output:\n"); fprintf(stderr, "\t\tfile:\t%s\n", word[0]); while (word[i] != NULL) { fprintf(stderr, "\t\targv[%d]:\t%s\n", i, word[i]); i++; } } Execvp(word[0], word); exit(0); } Waitpid(pid, &status,0); gettimeofday(&tv2, 0); t = (1000.0*tv2.tv_sec + tv2.tv_usec/1000.0) - (1000.0*tv1.tv_sec + tv1.tv_usec/1000.0); fprintf (stderr, "Elapsed Time: %d sec, %d msec\n", (int) t/1000, (int) t%1000); }