-
Notifications
You must be signed in to change notification settings - Fork 222
/
Copy pathshell.c
44 lines (36 loc) · 844 Bytes
/
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
static void die(const char *s)
{
perror(s);
exit(1);
}
int main()
{
char buf[100];
pid_t pid;
int status;
printf("AP> ");
while (fgets(buf, sizeof(buf), stdin) != NULL) {
if (buf[strlen(buf) - 1] == '\n')
buf[strlen(buf) - 1] = 0; // replace newline with '\0'
pid = fork();
if (pid < 0) {
die("fork error");
} else if (pid == 0) {
// child process
execl(buf, buf, (char *)0);
die("execl failed");
} else {
// parent process
if (waitpid(pid, &status, 0) != pid)
die("waitpid failed");
}
printf("AP> ");
}
return 0;
}