/
fork.c
144 lines (126 loc) · 2.44 KB
/
fork.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#include "fork.h"
#include "editor.h"
static int dup_close_on_exec(int old, int new)
{
if (dup2(old, new) < 0)
return -1;
fcntl(new, F_SETFD, FD_CLOEXEC);
return new;
}
static void handle_child(char **argv, int fd[3], int error_fd)
{
int i, error, nr_fds = 3;
int move = error_fd < nr_fds;
int max = error_fd;
/*
* Find if we must move fds out of the way.
*/
for (i = 0; i < nr_fds; i++) {
if (fd[i] > max)
max = fd[i];
if (fd[i] < i)
move = 1;
}
if (move) {
int next_free = max + 1;
if (error_fd < nr_fds) {
error_fd = dup_close_on_exec(error_fd, next_free++);
if (error_fd < 0)
goto out;
}
for (i = 0; i < nr_fds; i++) {
if (fd[i] < i) {
fd[i] = dup_close_on_exec(fd[i], next_free++);
if (fd[i] < 0)
goto out;
}
}
}
/*
* Now it is safe to duplicate fds in this order.
*/
for (i = 0; i < nr_fds; i++) {
if (i == fd[i]) {
// Clear FD_CLOEXEC flag
fcntl(fd[i], F_SETFD, 0);
} else {
if (dup2(fd[i], i) < 0)
goto out;
}
}
/*
* Unignore signals. See man page exec(3p) for more information.
*/
set_signal_handler(SIGINT, SIG_DFL);
set_signal_handler(SIGQUIT, SIG_DFL);
execvp(argv[0], argv);
out:
error = errno;
error = write(error_fd, &error, sizeof(error));
exit(42);
}
void close_on_exec(int fd)
{
fcntl(fd, F_SETFD, FD_CLOEXEC);
}
int pipe_close_on_exec(int fd[2])
{
int ret = pipe(fd);
if (ret == 0) {
close_on_exec(fd[0]);
close_on_exec(fd[1]);
}
return ret;
}
int fork_exec(char **argv, int fd[3])
{
int pid, rc, status, error = 0;
int ep[2];
if (pipe_close_on_exec(ep))
return -1;
pid = fork();
if (pid < 0) {
error = errno;
close(ep[0]);
close(ep[1]);
errno = error;
return pid;
}
if (!pid)
handle_child(argv, fd, ep[1]);
close(ep[1]);
rc = read(ep[0], &error, sizeof(error));
if (rc > 0 && rc != sizeof(error))
error = EPIPE;
if (rc < 0)
error = errno;
close(ep[0]);
if (!rc) {
// child exec was successful
return pid;
}
while (waitpid(pid, &status, 0) < 0 && errno == EINTR)
;
errno = error;
return -1;
}
int wait_child(int pid)
{
int status;
while (waitpid(pid, &status, 0) < 0) {
if (errno == EINTR)
continue;
return -errno;
}
if (WIFEXITED(status))
return (unsigned char)WEXITSTATUS(status);
if (WIFSIGNALED(status))
return WTERMSIG(status) << 8;
if (WIFSTOPPED(status))
return WSTOPSIG(status) << 8;
#if defined(WIFCONTINUED)
if (WIFCONTINUED(status))
return SIGCONT << 8;
#endif
return -EINVAL;
}