1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <sys/stat.h>
20 #include <unistd.h>
21 #include <sys/fcntl.h>
22
23 #include <spawn.h>
24 #include <sys/wait.h>
25
26 int main(
int argc,
char **argv) {
27 int ret;
28
29
30
31 int pout[
2];
32 if(pipe(pout)) {
33 perror(
"pipe");
34 return 1;
35 }
36
37
38 posix_spawn_file_actions_t actions;
39
40
41
42 posix_spawn_file_actions_init(&actions);
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61 posix_spawn_file_actions_adddup2(&actions, pout[
1],
1);
62
63
64
65
66
67
68
69
70
71
72 char *args[
10];
73 args[
0] =
"/bin/printf";
74 args[
1] =
"%s\n%f\n%s\n";
75 args[
2] =
"Hello World";
76 args[
3] =
"3.14";
77 args[
4] =
"posix_spawn test";
78 args[
5] =
NULL;
79
80
81 char *env[
10];
82 env[
0] =
"LC_ALL=C";
83 env[
1] =
NULL;
84
85
86 pid_t child;
87 ret = posix_spawn(
88 &child,
89 "/bin/printf",
90 &actions,
91 NULL,
92 args,
93 env);
94 posix_spawn_file_actions_destroy(&actions);
95 if(ret) {
96
97 perror(
"posix_spawn");
98 return 1;
99 }
100
101
102
103
104 close(pout[
1]);
105
106
107 char buf[
1024];
108 ssize_t r;
109 int linestart =
1;
110 while((r=read(pout[
0], buf,
1024)) >
0) {
111
112 for(
int i=
0;i<r;i++) {
113 if(linestart) {
114
115 printf(
"stdout: [");
116 linestart =
0;
117 }
118 if(buf[i] ==
'\n') {
119 printf(
"]\n");
120 linestart =
1;
121 }
else {
122 putchar(buf[i]);
123 }
124 }
125 }
126
127
128 int status;
129 waitpid(child, &status,
0);
130
131 return 0;
132 }
133
134