From 265008c76d2472a464a2d885d13e6d71676addfb Mon Sep 17 00:00:00 2001 From: Nicolas Berr Date: Thu, 22 Sep 2011 15:39:20 +0200 Subject: [PATCH] - shell now supports multiple args in command line - executes binaries in /bin/ now --- newlib/examples/mshell.c | 60 ++++++++++++++++++++++++++++++++++------ 1 file changed, 51 insertions(+), 9 deletions(-) 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);