diff --git a/newlib/examples/mshell.c b/newlib/examples/mshell.c index fbd777b2..74323f3b 100644 --- a/newlib/examples/mshell.c +++ b/newlib/examples/mshell.c @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #undef errno @@ -38,31 +39,72 @@ void help() { printf("exit > exit shell \n"); } +#define MAXARGS 16 + +#define ST_WHITE 0 +#define ST_ARG 1 + +char** splitargs(char* args) { + static char* ret[MAXARGS+1]; + int i = 0; + int state = ST_WHITE; + while (*args != '\0') { + if (state == ST_WHITE) { + if (!isspace(*args)) { + ret[i++] = args; + if (i == MAXARGS) + break; + state = ST_ARG; + } + } + else { + if (isspace(*args)) { + *args = '\0'; + state = ST_WHITE; + } + } + args++; + } + ret[i] = NULL; + + return ret; +} + int main(int argc, char** argv) { - char* command = malloc(1024*sizeof(char)); + char commandline[1024]; + char* command; int size = 0, status = 0; pid_t pid; system("clear"); showlogo(); while(1) { - printf("$ "); - do { - size = scanf("%s", command); - } while(size <= 0); + char** newargv; + char* newenv[] = {"USER=root", "PATH=/bin:/sbin:/usr/bin", "PWD=/", "TEMP=/tmp", NULL}; + + printf("mshell> "); + gets(commandline); + + newargv = splitargs(commandline); + command = newargv[0]; + + if(command == NULL) { + continue; + } if(!strcmp(command, "exit")) { return 0; } if(!strcmp(command, "help")) { help(); } else { + char path[128]; + sprintf(path, "/bin/%s", command); pid = fork(); if (pid == 0) { //child - char* newargv[] = {command, NULL}; - char* newenv[] = {"USER=root", "PATH=/bin:/sbin:/usr/bin", "PWD=/", "TEMP=/tmp", NULL}; - - execve(command, newargv, newenv); + status = execve(path, newargv, newenv); + if (status) + printf("mshell: %s: command not found\n", path); return errno; } else { wait(&status);