-
Notifications
You must be signed in to change notification settings - Fork 48
/
shell.c
61 lines (54 loc) · 1.45 KB
/
shell.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
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define MAX_LEN_LINE 100
int main(void)
{
char command[MAX_LEN_LINE];
char *args[] = {command, NULL};
int ret, status;
pid_t pid, cpid;
while (true) {
char *s;
int len;
printf("MyShell $ ");
s = fgets(command, MAX_LEN_LINE, stdin);
if (s == NULL) {
fprintf(stderr, "fgets failed\n");
exit(1);
}
len = strlen(command);
printf("%d\n", len);
if (command[len - 1] == '\n') {
command[len - 1] = '\0';
}
printf("[%s]\n", command);
pid = fork();
if (pid < 0) {
fprintf(stderr, "fork failed\n");
exit(1);
}
if (pid != 0) { /* parent */
cpid = waitpid(pid, &status, 0);
if (cpid != pid) {
fprintf(stderr, "waitpid failed\n");
}
printf("Child process terminated\n");
if (WIFEXITED(status)) {
printf("Exit status is %d\n", WEXITSTATUS(status));
}
}
else { /* child */
ret = execve(args[0], args, NULL);
if (ret < 0) {
fprintf(stderr, "execve failed\n");
return 1;
}
}
}
return 0;
}