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