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
|
/*
https://bugs.gentoo.org/364877
written by Victor Stinner <victor.stinner@haypocalc.com>
*/
#include "headers.h"
static void cloexec(int fd)
{
int flags;
flags = fcntl(fd, F_GETFD);
if (flags == -1) {
perror("fcntl(F_GETFD)");
exit(1);
}
fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
}
int main(int argc, char *argv[])
{
int err;
pid_t child;
int outpipe[2];
int errpipe[2];
ssize_t n;
char buffer[4096];
char *dir = dirname(argv[0]);
char *argv0 = "pipe-fork_static_tst";
char *child_argv[] = {argv0, NULL};
if (dir)
if (chdir(dir)) {}
err = pipe(outpipe);
if (err) {
perror("open");
return 1;
}
err = pipe(errpipe);
if (err) {
perror("open");
return 1;
}
cloexec(errpipe[0]);
cloexec(errpipe[1]);
child = fork();
if (child < 0) {
perror("fork");
return 1;
}
if (child == 0) {
close(outpipe[0]);
close(errpipe[0]);
dup2(outpipe[1], 1);
execvp(argv0, child_argv);
execv(argv0, child_argv);
perror("execvp");
return 1;
} else {
close(outpipe[1]);
close(errpipe[1]);
printf("wait errpipe..."); fflush(stdout);
n = read(errpipe[0], buffer, sizeof(buffer));
if (n < 0) {
perror("fcntl(F_GETFD)");
return 1;
}
printf(" done ");
while (1) {
n = read(outpipe[0], buffer, sizeof(buffer));
if (n < 0) {
perror("fcntl(F_GETFD)");
return 1;
}
if (n == 0)
break;
}
int status;
waitpid(child, &status, 0);
if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
printf("OK!");
return 0;
}
printf("\nfailed! child status: %#x\n", status);
return 1;
}
}
|