-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
105 lines (90 loc) · 2.85 KB
/
main.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
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
// created using this tutorial: 'https://indradhanush.github.io/blog/writing-a-unix-shell-part-1/'
char **get_input(char*);
#define BUFFER_LEN 100
int main() {
printf("Welcome to MSchell\n");
pid_t child_pid;
char input[BUFFER_LEN];
char **command;
while (1) {
printf("~~~~(Ɛ:> ");
fgets(input, BUFFER_LEN, stdin);
// the input from fgets is newline terminated, I need a null terminated string
input[(strlen(input) - 1)] = '\0';
command = get_input(input);
if (strcmp(command[0], "cd") == 0) {
if (chdir(command[1]) < 0) {
perror(command[1]);
continue;
}
command[0] = "pwd";
command[1] = NULL;
} else if (strcmp(command[0], "exit") == 0) {
printf("Goodbye <3\n");
exit(0);
} else if (strcmp(command[0], "helpme") == 0) {
printf("Type 'exit' to exit\n");
continue;
}
child_pid = fork();
if (child_pid == 0) { // if this is the child process
if (execvp(command[0], command) < 0) {
perror(command[0]);
exit(1);
}
} else if (child_pid < 0) {
perror("Fork failed");
exit(1);
} else { // main process
int stat_loc;
pid_t wait_result = waitpid(child_pid, &stat_loc, WUNTRACED);
}
free(command);
}
free(input);
return 0;
}
char **get_input(char* input) {
int buffer_len = 8;
// the output char array
char **command = malloc(buffer_len * sizeof(char *));
if (command == NULL) {
perror("Malloc failed");
exit(1);
}
// commands are separated by a space
char *separator = " ";
// the currently parse word
char *parsed;
// index :)
int index = 0;
// first word
parsed = strtok(input, separator);
while (parsed != NULL) {
// assign the word to the command array
command[index] = parsed;
index++;
// as from the man page
// In each subsequent call that should parse the same string, str must be NULL.
parsed = strtok(NULL, separator);
// if the buffer is not large enough
if (index > buffer_len) {
printf("realloc\n");
buffer_len *= 2;
command = realloc(command, buffer_len * sizeof(char *));
if (command == NULL) {
perror("realloc failed");
exit(1);
}
}
}
// NULL terminated thing
command[index] = NULL;
return command;
}