|
0
|
1 #include <iostream> |
|
|
2 #include <unistd.h> |
|
|
3 #include <spawn.h> |
|
|
4 #include <cstring> |
|
|
5 #include <string> |
|
|
6 #include <sys/wait.h> |
|
|
7 #include "process.h" |
|
|
8 extern char** environ; |
|
|
9 std::string run_piped(const char* path, char* const argv[], const std::string& input) |
|
|
10 { |
|
|
11 int status; |
|
|
12 pid_t pid; |
|
|
13 int pipeA[2]; |
|
|
14 int pipeB[2]; |
|
|
15 if (pipe(pipeA) < 0) |
|
|
16 return "error"; |
|
|
17 if (pipe(pipeB) < 0) |
|
|
18 return "error"; |
|
|
19 posix_spawn_file_actions_t actions; |
|
|
20 posix_spawn_file_actions_init(&actions); // initialize actions |
|
|
21 posix_spawn_file_actions_adddup2(&actions, pipeA[0], STDIN_FILENO); |
|
|
22 posix_spawn_file_actions_adddup2(&actions, pipeB[1], STDOUT_FILENO); |
|
|
23 posix_spawn_file_actions_addclose(&actions, pipeA[1]); // closes write end in child |
|
|
24 posix_spawn_file_actions_addclose(&actions, pipeB[0]); // makes sure child doesn't read its own output pipe |
|
|
25 posix_spawn_file_actions_addclose(&actions, pipeA[0]); // close read fd in child |
|
|
26 posix_spawn_file_actions_addclose(&actions, pipeB[1]); // close read fd in child, part 2 |
|
|
27 status = posix_spawn(&pid, path, &actions, NULL, const_cast<char* const*>(argv), environ); |
|
|
28 close(pipeA[0]); |
|
|
29 close(pipeB[1]); |
|
|
30 if (status != 0) { |
|
|
31 posix_spawn_file_actions_destroy(&actions); |
|
|
32 close(pipeA[1]); |
|
|
33 close(pipeB[0]); |
|
|
34 std::cerr << "posix_spawn failed: " << strerror(status) << std::endl; |
|
|
35 return "error"; |
|
|
36 } |
|
|
37 write(pipeA[1],input.c_str(), input.size()); |
|
|
38 close(pipeA[1]); |
|
|
39 char buf[256]; |
|
|
40 std::string result; |
|
|
41 ssize_t n; |
|
|
42 while ((n = read(pipeB[0], buf, sizeof(buf))) > 0) { |
|
|
43 result.append(buf, n); |
|
|
44 } |
|
|
45 close(pipeB[0]); |
|
|
46 if (waitpid(pid, &status, 0) == -1) { |
|
|
47 posix_spawn_file_actions_destroy(&actions); |
|
|
48 close(pipeA[1]); |
|
|
49 close(pipeB[0]); |
|
|
50 perror("waitpid"); |
|
|
51 return "error"; |
|
|
52 } |
|
|
53 posix_spawn_file_actions_destroy(&actions); |
|
|
54 return result; |
|
|
55 } |