-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmyshell.c
106 lines (102 loc) · 2.57 KB
/
myshell.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#define CYAN "\x1b[36m"
#define GREEN "\x1b[32m"
#define MAGENTA "\x1b[35m"
#define RED "\x1b[31m"
#define RESET "\x1b[0m"
const char * const DELIMITERS = " \t\n()<>|&;";
int main(void){
char *input = malloc(sizeof(char)*500), *cwd = malloc(sizeof(char)*300), *iterator, *mode, *homedir = getenv("HOME"), *user = malloc(sizeof(char)*50);
getlogin_r(user, 49);
while(1){
mode = NULL;
getcwd(cwd, sizeof(char)*299);
if(strstr(cwd, homedir)){
printf(MAGENTA "# " GREEN "%s@myshell " CYAN "~%s \n" MAGENTA "$ " RESET, user, cwd+strlen(homedir));
}else{
printf(MAGENTA "# " GREEN "%s@myshell " CYAN "%s \n" MAGENTA "$ " RESET, user, cwd);
}
if(fgets(input, 499, stdin) && *input != '\n'){
iterator = strstr(input, ">>");
if(iterator){
mode = "a";
}else{
iterator = strstr(input, ">");
if(iterator){
mode = "w";
}else{
iterator = strstr(input, "<");
if(iterator){
mode = "r";
}
}
}
iterator = strtok(input, DELIMITERS);
if(!strcmp(iterator, "exit")){
free(input);
free(user);
free(cwd);
exit(EXIT_SUCCESS);
}else if(!strcmp(iterator, "cd")){
iterator = strtok(NULL, DELIMITERS);
if(!iterator){
iterator = homedir;
}
if(chdir(iterator) == -1){
printf(RED "cd: %s\n" RESET, strerror(errno));
}
}else{
pid_t pid = fork();
if(pid == 0){
char *arguments[20];
int i = 0;
arguments[0] = iterator;
while (arguments[i]){
arguments[++i] = strtok(NULL, DELIMITERS);
}
if(mode){
FILE *f;
if(arguments[--i]){
if(mode == "r"){
f = freopen(arguments[i], "r", stdin);
}else{
f = freopen(arguments[i], mode, stdout);
}
arguments[i] = NULL;
}
if(f == NULL){
printf(RED "Error: %s\n" RESET, strerror(errno));
}
}
if(execvp(arguments[0], arguments) == -1){
if(errno == 2){
printf(RED "Error: Command not found: %s\n" RESET, arguments[0]);
}else{
printf(RED "Error: %s\n" RESET, strerror(errno));
}
}
free(input);
free(user);
free(cwd);
exit(EXIT_SUCCESS);
}else if(pid > 0){
if(wait(NULL) == -1){
printf(RED "Error: %s\n" RESET, strerror(errno));
}
}else if(pid == -1){
printf(RED "Error: %s\n" RESET, strerror(errno));
}
}
}
}
free(input);
free(user);
free(cwd);
return 0;
}