-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopen2_test.cc
More file actions
44 lines (36 loc) · 1.06 KB
/
Copy pathpopen2_test.cc
File metadata and controls
44 lines (36 loc) · 1.06 KB
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 "popen2.h"
#include <cassert>
void write_data(subprocess_t& p, const char* data)
{
// write data to p's stdin
fprintf(p.p_stdin, "%s", data);
fflush(p.p_stdin); // IMPORTANT, to make sure child receives the data
}
void read_data(const subprocess_t& p, char* data)
{
// read data from p's stdout
fscanf(p.p_stdout, "%s", data);
//fflush(p.p_stdout);
}
int main()
{
char buf[5][10]{};
subprocess_t subprocess = popen2("cat");
assert(subprocess.cpid != -1);
// communicate with the subprocess
// for the test subprocess `cat`, we need a '\n' in each write
write_data(subprocess, "one\n");
read_data(subprocess, buf[0]);
write_data(subprocess, "two\n");
write_data(subprocess, "three\n");
read_data(subprocess, buf[1]);
read_data(subprocess, buf[2]);
write_data(subprocess, "four\n");
read_data(subprocess, buf[3]);
write_data(subprocess, "five\n");
read_data(subprocess, buf[4]);
pclose2(&subprocess);
for (char * s : buf)
fprintf(stdout, "%s\n", s);
return 0;
}