blob: 7372d2d5c2eeac3e9d6d79d2b3bc00351be0a41d (
plain)
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
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#define MAXLINE 80
int shell() {
char line[MAXLINE];
char *args[MAXLINE / 2 + 1];
int should_run = 1;
while (should_run) {
printf(">");
fflush(stdout);
if (!fgets(line, MAXLINE, stdin)) {
break;
}
line[strlen(line) - 1] = '\0';
int i = 0;
args[i] = strtok(line, " ");
while (args[i] != NULL) {
i++;
args[i] = strtok(NULL, " ");
}
if (args[0] == NULL) {
continue;
}
if (strncmp(args[0], "exit", 4) == 0) {
break;
}
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return 1;
} else if (pid == 0) {
if (execvp(args[0], args) == -1) {
perror("execvp");
}
return 1;
} else {
wait(NULL);
}
}
}
|