forked from xxyzz/ostep-hw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
4.c
106 lines (95 loc) · 2.61 KB
/
4.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#define _GNU_SOURCE // for execvpe()
#if __has_include(<features.h>)
# include <features.h> // __GNU_LIBRARY__
#endif
#include <fcntl.h> // open
#include <stdio.h> // perror
#include <stdlib.h> // exit
#include <sys/wait.h>
#include <unistd.h> // fork, exec*, fexecve
#define errExit(msg) \
do { \
perror(msg); \
exit(EXIT_FAILURE); \
} while (0)
int main() { // APUE 8.10
char *argv[] = {"ls", "-l", "-a", "-h", (char *)NULL};
char *envp[] = {"PATH=/bin:/usr/bin", NULL};
pid_t cpid = fork();
if (cpid == -1)
errExit("fork");
else if (cpid == 0) {
printf("execl:\n");
if (execl("/bin/ls", "ls", "-l", "-a", "-h", (char *)NULL) == -1)
errExit("execl");
}
if (wait(NULL) == -1)
errExit("wait");
if ((cpid = fork()) == -1)
errExit("fork");
else if (cpid == 0) {
printf("\nexeclp:\n");
if (execlp("ls", "ls", "-l", "-a", "-h", (char *)NULL) == -1)
errExit("execlp");
}
if (wait(NULL) == -1)
errExit("wait");
if ((cpid = fork()) == -1)
errExit("fork");
else if (cpid == 0) {
printf("\nexecle:\n");
if (execle("/bin/ls", "ls", "-l", "-a", "-h", (char *)NULL, envp) == -1)
errExit("execle");
}
if (wait(NULL) == -1)
errExit("wait");
if ((cpid = fork()) == -1)
errExit("fork");
else if (cpid == 0) {
printf("\nexecv:\n");
if (execv("/bin/ls", argv) == -1)
errExit("execv");
}
if (wait(NULL) == -1)
errExit("wait");
if ((cpid = fork()) == -1)
errExit("fork");
else if (cpid == 0) {
printf("\nexecvp:\n");
if (execvp("ls", argv) == -1)
errExit("execvp");
}
if (wait(NULL) == -1)
errExit("wait");
if ((cpid = fork()) == -1)
errExit("fork");
else if (cpid == 0) {
printf("\nexecve:\n");
if (execve("/bin/ls", argv, envp) == -1) // system call
errExit("execve");
}
#ifdef __GNU_LIBRARY__
if (wait(NULL) == -1)
errExit("wait");
if ((cpid = fork()) == -1)
errExit("fork");
else if (cpid == 0) {
printf("\nexecvpe:\n");
if (execvpe("ls", argv, envp) == -1)
errExit("execvpe");
}
if (wait(NULL) == -1)
errExit("wait");
if ((cpid = fork()) == -1)
errExit("fork");
else if (cpid == 0) {
printf("\nfexecve:\n");
int fd = 0;
if ((fd = open("/bin/ls", O_PATH)) == -1)
errExit("open");
if (fexecve(fd, argv, envp) == -1)
errExit("fexecve");
}
#endif
return 0;
}