1 #include <stdio.h> 2 #include <unistd.h> 3 #include <stdlib.h> 4 #include <sys/types.h> 5 #include <sys/stat.h> 6 #include <fcntl.h> 7 #include <string.h> 8 #include <sys/wait.h> 9 #include "version.h" 10 #include "sh.h" 11 12 extern char *optarg; 13 extern char **environ; 14 extern int optind, opterr, optopt; 15 16 int sh_main (int argc, char **argv) { 17 char *buff; 18 char ch; 19 int infrom=STDIN_FILENO; 20 int i=0,x; 21 22 while ( (ch=getopt(argc,argv,"isc:-")) != -1) { 23 switch (ch) { 24 case 'c': 25 if ((infrom=open(optarg,O_RDONLY))<0) { 26 perror("sh"); 27 return(-1); 28 } 29 case 's': 30 case 'i': 31 case '-': 32 default: 33 return(-1); 34 } 35 } 36 37 buff=calloc(4096, 1); 38 /* TODO: Make Environment variable PS1 supported */ 39 write(STDOUT_FILENO, "shell# ", 7); 40 while (1) { 41 if (read(infrom, &ch, 1)<1) break; 42 if (ch==13 || ch==10) { 43 x=strlen(buff); 44 if (buff[x-1]=='\\') { 45 i--; 46 buff[x-1]=' '; 47 /* TODO: Make Environment variable PS2 supported */ 48 write(STDOUT_FILENO, "> ", 2); 49 goto loop; 50 } 51 sh_process_command(buff); 52 free(buff); 53 buff=calloc(4096, 1); 54 i=0; 55 write(STDOUT_FILENO, "shell# ", 7); 56 goto loop; 57 } 58 buff[i++]=ch; 59 loop: 60 } 61 return(0); 62 } 63 64 int sh_process_command (char *value) { 65 char *argv[128]; 66 char valuecp[1024]; 67 int i=0,x; 68 int status, retval=0; 69 70 strncpy(valuecp, value, sizeof(valuecp)); 71 72 argv[i]=strtok(value, " "); 73 while (1) { 74 if (argv[i]==NULL) break; 75 argv[++i]=strtok(NULL, " "); 76 } 77 78 if (argv[0]==NULL) return(0); 79 80 if (!strcmp(argv[0],"exit")) { 81 if (argv[1]==NULL) { exit(0); } else { exit(atoi(argv[1])); } 82 } 83 if (!strcmp(argv[0],"cd")) { 84 if (chdir(argv[1])<0) { 85 write(STDERR_FILENO, "sh: ", 4); 86 perror("cd"); 87 } 88 return(0); 89 } 90 91 92 if ((x=fork())!=0) { 93 waitpid(x,&status,0); 94 if (WIFEXITED(status)) retval=WEXITSTATUS(status); 95 if (retval) { 96 printf("[%i]+ %-15i %s\n",x,retval,valuecp); 97 } 98 return(retval); 99 } 100 101 if (execvp(argv[0], argv)<0) { 102 write(STDERR_FILENO, "sh: ", 5); 103 perror(argv[0]); 104 } 105 exit(127); 106 } |