This commit is contained in:
Pin
2022-03-30 21:26:17 -04:00
parent 5224c62e35
commit 28940ba8ee
5 changed files with 81 additions and 13 deletions

65
msh.c
View File

@@ -10,6 +10,7 @@
#include "msh.h"
#define clear() printf("\033[H\033[J")
#define MATHLEN 10
union pipe {
int fileDesc[2];
@@ -21,12 +22,14 @@ union pipe {
static char *builtinFunctions[] = {
"exit",
"author"
"author",
"cd"
};
int (*builtinFunc[]) (char *) = {
int (*builtinFunc[]) (char **) = {
&builtinExit,
&builtinAuthor
&builtinAuthor,
&builtinCD
};
int builtinExit() {
@@ -43,6 +46,20 @@ int builtinAuthor() {
return 0;
}
int builtinCD(char **dir) {
int status = 0;
if (dir != NULL) {
if (chdir(dir[1]) != 0) {
status = 1;
printf("bash: cd: error\n");
}
} else {
status = 1;
printf("bash: cd: error\n");
}
return status;
}
void failedTest() {
static const char* message =
"\n"
@@ -74,10 +91,39 @@ int runCommand(char *command) {
return status;
}
char **splitCMD(char *line) {
size_t size = 8;
size_t pos = 0;
char **args = calloc(0, size * sizeof(char*));
char *arg = NULL;
if(line == NULL) {
*args=NULL;
return args;
}
arg = strtok(line, " \t\r\n\a");
while (arg != NULL) {
args[pos] = arg;
pos++;
if (pos >= size) {
size += 1;
args = realloc(args, size * sizeof(char*));
}
arg = strtok(NULL, " \t\r\n\a");
}
args[pos] = NULL;
return args;
}
int execCommand(char *command) {
char **commandARGS = splitCMD(command);
for (size_t i = 0; i < (sizeof(builtinFunctions) / sizeof(char *)); i++) {
if (strcmp(command, builtinFunctions[i]) == 0) {
return (*builtinFunc[i])(command);
if (strcmp(commandARGS[0], builtinFunctions[i]) == 0) {
return (*builtinFunc[i])(commandARGS);
}
}
return runCommand(command);
@@ -92,6 +138,7 @@ void initShell() {
// Setting random time seed
srand(time(0));
fflush(stdout);
runCommand("uname -a");
fd = fopen("/etc/motd", "r");
@@ -104,10 +151,10 @@ void initShell() {
c = fgetc(fd);
}
fclose(fd);
} else {
printf("MOTD is empty\n");
}
printf("\n");
return;
}
@@ -178,8 +225,8 @@ int randomNum(int limit) {
int mathTest() {
int status = 0;
int numAnswer = 0;
int num1 = randomNum(10);
int num2 = randomNum(10);
int num1 = randomNum(MATHLEN);
int num2 = randomNum(MATHLEN);
char *numLine = NULL;
printf("%d + %d = ", num1, num2);
numLine = readline("");