toaruos/userspace/esh.c

86 lines
1.6 KiB
C
Raw Normal View History

2011-12-07 05:46:35 +04:00
/*
* E-Shell
*
* Test shell for ToAruOS
*/
#include <stdio.h>
#include <stdint.h>
#include <syscall.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
2011-12-07 06:13:20 +04:00
DEFN_SYSCALL1(wait, 17, unsigned int);
2011-12-07 05:46:35 +04:00
int main(int argc, char ** argv) {
printf("I am pid %d\n", getpid());
char cwd[1024] = {'/',0};
2011-12-08 01:08:40 +04:00
2011-12-07 05:46:35 +04:00
int pid = getpid();
2011-12-08 01:08:40 +04:00
int nowait = 0;
int free_cmd = 0;
2011-12-07 05:46:35 +04:00
while (1) {
2011-12-08 01:08:40 +04:00
char * cmd = malloc(sizeof(char) * 1024);
2011-12-07 05:46:35 +04:00
printf("%s$ ", cwd);
fflush(stdout);
fgets(cmd, 1024, stdin);
cmd[strlen(cmd)-1] = '\0';
char *p, *tokens[512], *last;
int i = 0;
for ((p = strtok_r(cmd, " ", &last)); p;
(p = strtok_r(NULL, " ", &last)), i++) {
if (i < 511) tokens[i] = p;
}
tokens[i] = NULL;
2011-12-07 06:36:40 +04:00
if (!tokens[0] || strlen(tokens[0]) < 1) {
2011-12-08 01:08:40 +04:00
free(cmd);
2011-12-07 06:36:40 +04:00
continue;
2011-12-07 05:46:35 +04:00
}
if (!strcmp(tokens[0],"exit")) {
goto exit;
}
2011-12-08 01:08:40 +04:00
nowait = (!strcmp(tokens[i-1],"&"));
/* Attempt to open the command */
FILE * file = fopen(tokens[0], "r");
if (!file) {
if (!strstr(tokens[0],"/")) {
cmd = malloc(sizeof(char) * (strlen(tokens[0]) + strlen("/bin/") + 1));
sprintf(cmd, "%s%s", "/bin/", tokens[0]);
file = fopen(cmd,"r");
if (!file) {
printf("Command not found: %s\n", tokens[0]);
free(cmd);
continue;
}
fclose(file);
} else {
printf("Command not found: %s\n", tokens[0]);
free(cmd);
continue;
}
} else {
fclose(file);
}
2011-12-07 05:46:35 +04:00
uint32_t f = fork();
if (getpid() != pid) {
2011-12-08 01:08:40 +04:00
int i = execve(cmd, tokens, NULL);
2011-12-07 06:36:40 +04:00
return i;
2011-12-07 05:46:35 +04:00
} else {
2011-12-08 01:08:40 +04:00
if (!nowait) {
int i = syscall_wait(f);
if (i) {
printf("[%d] ");
}
2011-12-07 06:36:40 +04:00
}
2011-12-08 01:08:40 +04:00
free(cmd);
2011-12-07 05:46:35 +04:00
}
}
exit:
return 0;
}