-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmini_shell.c
More file actions
43 lines (39 loc) · 982 Bytes
/
Copy pathmini_shell.c
File metadata and controls
43 lines (39 loc) · 982 Bytes
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
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#define MAX_ARGS 20
int main() {
char input[256];
while (1) {
printf("Mini-Shell> ");
fflush(stdout);
if (!fgets(input, sizeof(input), stdin))
break;
input[strcspn(input, "\n")] = '\0';
if (strlen(input) == 0) continue;
if (strcmp(input, "exit") == 0) {
break;
}
char *args[MAX_ARGS];
int i = 0;
char *token = strtok(input, " ");
while (token != NULL && i < MAX_ARGS - 1) {
args[i++] = token;
token = strtok(NULL, " ");
}
args[i] = NULL;
int pid = fork();
if (pid == 0) {
execvp(args[0], args);
perror("exec failed");
exit(1);
} else if (pid > 0) {
wait(NULL);
} else {
perror("fork failed");
}
}
return 0;
}