/****************************************************************** * Created: Josep Valls 20080211 * Simple shell for CMPS105/Winter2008 * Practice the use of standard IO and signals * Features: reads whole line, multiple arguments * Wishlist: command history, multiple commands using ;, pipes ******************************************************************/ #include #include #include #include #include #include #include #include #include #include const MAXJOBS = 20; const ICSIZE = 255; typedef struct{ pid_t pid; int status; char commandline[255]; } s_jobs; static void sig_int(int); int main(int argc, char *argv[]) { char buf[ICSIZE],bufbak[ICSIZE]; pid_t pid; int status; char *args[ICSIZE]; char *u, *b; int argsc=0; s_jobs jobs[MAXJOBS]; int jobsc=0; int i=0; int jobsr=0; //add the signal listener if(signal(SIGINT,sig_int)==SIG_ERR) printf("Error in the signal catching mechanics\n"); if(signal(SIGUSR1,sig_int)==SIG_ERR) printf("Error in the signal catching mechanics\n"); //test by kill -USR1 pid //main loop do{ printf("\nCommand: "); if(fgets(buf,sizeof(buf),stdin)==NULL){ continue; } //shell commands filter if(strcmp(buf,"exit\n")==0) continue; if(strcmp(buf,"jobs\n")==0) { printf("job\tpid\tstatus\tcommand line\n"); for(i=0;i=0;i--){ jobs[i+1]=jobs[i]; } jobsc++; jobs[0].pid=0; jobs[0].status=-1; strcpy(jobs[0].commandline,buf); //parse the string strcpy(bufbak,buf); argsc=0; u= strtok_r(buf, " \n", &b); while (u) { args[argsc]= u; argsc++; u= strtok_r(NULL, " \n", &b); } args[argsc--]= NULL; //execute the command pid=fork(); if(pid==0){ //this is the child jobs[0].pid=getpid(); execvp(args[0],args); printf("error executing %s from the command line %s\n",args[0],bufbak); exit(127); //without this exit, there will be two processes and the exit command would not success } else //this is the parent wait(&status); }while(strcmp(buf,"exit\n")!=0); //free(buf); printf("Goodbye!\n"); } //signal catching function static void sig_int(int signum){ printf("\nSignal catched %d\n",signum); printf("\nCommand: "); //why is this string being printed before the signal catched string? }