metalsvm/newlib/examples/mshell.c
Nicolas Berr 265008c76d - shell now supports multiple args in command line
- executes binaries in /bin/ now
2011-09-22 15:39:20 +02:00

116 lines
2.5 KiB
C

/*
* Copyright 2011 Marian Ohligs, Chair for Operating Systems,
* RWTH Aachen University
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/wait.h>
#undef errno
extern int errno;
void showlogo() {
printf("\n\n");
printf("================================================================================\n");
printf(" m(etalsvm)shell\n\n");
printf("================================================================================\n");
}
void help() {
printf("possible commands: \n");
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 commandline[1024];
char* command;
int size = 0, status = 0;
pid_t pid;
system("clear");
showlogo();
while(1) {
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
status = execve(path, newargv, newenv);
if (status)
printf("mshell: %s: command not found\n", path);
return errno;
} else {
wait(&status);
}
}
}
return errno;
}