Repository navigation
Expand file tree
/
Copy pathshell.c
More file actions
71 lines (56 loc) · 1.79 KB
/
Copy pathshell.c
File metadata and controls
71 lines (56 loc) · 1.79 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
#include "k2sh.h"
void shell_init(shell_state_t* state) {
if (getcwd(state->cwd, sizeof(state->cwd)) == NULL) {
perror("ksh: getcwd() error");
strcpy(state->cwd, "/");
}
state->last_exit_status = 0;
state->should_exit = 0;
printf("KSH - Simple Shell v1.0\n");
printf("Type 'help' for available commands.\n");
}
void shell_mainloop(shell_state_t* state) {
char* input;
char** args;
char prompt[MAX_PROMPT_SIZE];
int status = 1;
while (status && !state->should_exit) {
update_prompt(state, prompt, sizeof(prompt));
printf("%s", prompt);
fflush(stdout);
input = input_string(stdin, 64);
if (strlen(input) == 0) {
free(input);
continue;
}
append_history(input);
if (strchr(input, '|') != NULL) {
int num_cmds;
char*** commands = parse_pipe(&num_cmds, input);
if (commands && num_cmds > 0) {
status = execute_pipeline(num_cmds, commands, state);
free_commands(commands, num_cmds);
}
} else {
args = split_args(input);
if (args && args[0]) {
status = execute_command(args, state);
}
free(args);
}
free(input);
}
}
void shell_cleanup(shell_state_t* state) {
free_history();
printf("Exiting...\n");
}
void update_prompt(shell_state_t* state, char* prompt, size_t size) {
if (getcwd(state->cwd, sizeof(state->cwd)) == NULL) {
perror("ksh: getcwd() error");
}
snprintf(prompt, size, "\033[1;32m%s\033[0m \033[1;34m>:\033[0m ", state->cwd);
}
void print_error(const char* message) {
fprintf(stderr, "\033[1;31mError:\033[0m %s\n", message);
}