-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmybash.c
More file actions
120 lines (102 loc) · 2.42 KB
/
mybash.c
File metadata and controls
120 lines (102 loc) · 2.42 KB
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#define MAX_INPUT 1024
#define MAX_ARGS 64
void shell_loop();
char *read_input();
char **parse_input(char *input);
int execute_command(char **args);
int shell_cd(char **args);
int shell_exit(char **args);
// Built-in command names and functions
char *builtin_str[] = { "cd", "exit" };
int (*builtin_func[]) (char **) = { &shell_cd, &shell_exit };
int num_builtins() { return sizeof(builtin_str) / sizeof(char *); }
int main() {
shell_loop();
return 0;
}
void shell_loop() {
char *input;
char **args;
int status;
do {
printf("mybash> ");
input = read_input();
args = parse_input(input);
status = execute_command(args);
free(input);
free(args);
} while (status);
}
char *read_input() {
char *buffer = malloc(MAX_INPUT);
if (!buffer) {
perror("malloc");
exit(EXIT_FAILURE);
}
if (fgets(buffer, MAX_INPUT, stdin) == NULL) {
free(buffer);
exit(EXIT_SUCCESS); // Handle Ctrl+D
}
// Remove newline character
buffer[strcspn(buffer, "\n")] = '\0';
return buffer;
}
char **parse_input(char *input) {
char **args = malloc(MAX_ARGS * sizeof(char *));
char *token;
int position = 0;
if (!args) {
perror("malloc");
exit(EXIT_FAILURE);
}
token = strtok(input, " ");
while (token != NULL) {
args[position++] = token;
token = strtok(NULL, " ");
}
args[position] = NULL;
return args;
}
int execute_command(char **args) {
if (args[0] == NULL) {
return 1; // Empty command
}
for (int i = 0; i < num_builtins(); i++) {
if (strcmp(args[0], builtin_str[i]) == 0) {
return (*builtin_func[i])(args);
}
}
pid_t pid = fork();
if (pid == 0) {
// Child process
if (execvp(args[0], args) == -1) {
perror("mybash");
}
exit(EXIT_FAILURE);
} else if (pid < 0) {
perror("fork");
} else {
// Parent process
int status;
waitpid(pid, &status, 0);
}
return 1;
}
int shell_cd(char **args) {
if (args[1] == NULL) {
fprintf(stderr, "mybash: expected argument to \"cd\"\n");
} else {
if (chdir(args[1]) != 0) {
perror("mybash");
}
}
return 1;
}
int shell_exit(char **args) {
return 0;
}