-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
58 lines (50 loc) · 1.23 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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
/* Simple shell program which reads user input,
* tokenizes commands, and implements program exit command
*/
int main() {
char input[100];
while(1) {
/* Display shell prompt and collect user input */
printf("shell>> ");
fflush(stdout);
fgets(input, 100, stdin);
/* Remove newline and implement exit and clear command */
input[strcspn(input, "\n")] = 0;
if (strcmp(input, "exit") == 0) {
break;
} else if (strcmp(input, "clear") == 0) {
printf("\033[H\033[J");
}
/* Create array of pointers to store command line arguments */
char *clargs[20];
char *token = strtok(input, " ");
int i = 0;
/* Create array of cli arguments */
while(token != NULL && i < 19) {
clargs[i] = token;
token = strtok(NULL, " ");
i++;
}
clargs[i] = NULL;
/* Fork and execute commands */
pid_t pid = fork();
if (pid < 0) {
perror("fork failure");
continue;
}
else if (pid == 0) {
execvp(clargs[0], clargs);
perror("command failed");
exit(EXIT_FAILURE);
}
else {
wait(NULL);
}
}
return 0;
}