/* * cs537 Project 1 - Shell * * Written by Stefan Strandberg (stefan@cs.wisc.edu) * $Id: main.c,v 1.8 2004/09/23 22:00:27 stefan Exp $ * */ #include #include #include #include #include #include "shell.h" #include "job.h" /* * TODO: * * Fix horrible memory leaks...they're better than they were, but they're still * there. * * Figure out why the heck my waitpid keeps getting -1. Maybe I'm reaping * Wrong or something. Meh. * */ int main(int argc, char *argv[]) { int should_exit = 0; int interactive = 1; int jobnum = 1; int c; FILE *fp = NULL; FILE *inbuffer = stdin; action_t action; int status; // turn off friggen buffering...it ruins our day!! setbuf(stdout, NULL); switch (argc) { case 1: break; case 2: fp = fopen(argv[1], "r"); if (fp == NULL) { fprintf(stderr, "Error: unable to open file %s\n", argv[1]); return 1; } interactive = 0; inbuffer = fp; break; default: fprintf(stderr, "Invalid number of command line arguments: %i\n", (argc - 1)); return 1; } shell_t *turtle_shell = create_shell(); job_t *jobs[MAX_JOBS]; // we aren't freeing these...memory leak!! while(!should_exit) { jobs[jobnum - 1] = malloc(sizeof(job_t)); if((jobs[jobnum - 1]) == NULL) { fprintf(stderr, "Unable to malloc() a job in main()!!\n"); exit(1); } action = run_shell(turtle_shell, interactive, &jobnum, jobs[jobnum - 1], inbuffer); switch (action) { case WAITERROR: fprintf(stderr, "Invalid jid\n"); break; case EXITVAL: should_exit = 1; break; case JOBVAL: do_jobcmd(jobs, jobnum); break; case NORMAL: break; // nothing, just run our loop again case CHILDEXIT: exit(1); default: if (action < (jobnum)) do_waitcmd(jobs[action - 1]); else printf("Invalid jid %d\n", action); } // reap our children here i guess. we're doing a lot of dumb // algorithms in this program (with reaping and the "j" command and // such, but I'm sleepy and I haven't gotten any sleep in forever. // this bad algorithm reaps zombies every command for (c = 0 ; c < jobnum - 1 ; c++) waitpid(jobs[c]->pid, &status, WNOHANG); } if (argc > 1) fclose(fp); for (c = 0 ; c < jobnum - 1; c++) { remove_job(jobs[c]); } return 0; }