Skip to content

Instantly share code, notes, and snippets.

@Miigon
Created March 21, 2021 10:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Miigon/f8367f16eaddb8eddcec584eba2f4255 to your computer and use it in GitHub Desktop.
Save Miigon/f8367f16eaddb8eddcec584eba2f4255 to your computer and use it in GitHub Desktop.
a minishell in C created for lab1 of my operating system course.
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include <stdlib.h>
#define prompt "\e[32mminishell\e[0m> "
void builtin_exit(char *argv[16]) {
exit(0);
}
void builtin_help(char *argv[16]) {
printf("====== minishell by miigon from SZU ======\n");
printf("type the name of a program to run.\n");
printf("use `help` to show the help message\n");
printf("use `exit` to exit the current shell\n");
}
typedef void(*builtin_func)(char*[16]);
const char *builtin_commands[] = {
"exit",
"help",
NULL
};
builtin_func builtin_funcs[] = {
builtin_exit,
builtin_help,
};
int getBuiltin(const char *prog) {
for(int i=0;builtin_commands[i] != NULL;i++) {
if(strcmp(prog, builtin_commands[i]) == 0) {
return i;
}
}
return -1;
}
int main() {
printf("minishell by Miigon from SZU (2021-03-21)\n");
while(1) {
printf(prompt);
char *line;
size_t size;
getline(&line, &size, stdin);
char args[16][4096];
char *argv[16];
char *p = line;
// process arguments
char argc = 1;
char i = 0;
while(*p!='\n' && *p!='\0') {
if(*p == ' ') {
args[argc-1][i++] = '\0';
argv[argc-1] = args[argc-1];
argc++;
i = 0;
} else {
args[argc-1][i++] = *p;
}
p++;
}
argv[argc-1] = args[argc-1];
args[argc-1][i++] = '\0';
argv[argc] = NULL;
int builtin_index;
if((builtin_index=getBuiltin(argv[0])) != -1) { // builtin functions
builtin_funcs[builtin_index](argv);
} else {
// execute
int pid = fork(); // fork the shell
if(pid == -1){
printf("failed creating child process\n");
} else if(pid == 0) { // child
// replace the child shell process image with the program
// to run, executing the program.
if(execvp(argv[0], argv) == -1) {
perror("execution failed");
exit(1);
};
} else { // parent (shell)
waitpid(pid, NULL, 0);
}
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment