fork_pipe.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* fork_pipe.cpp - fork, exec & setup pipe helper
  2. * Copyright (C) 2017 caryoscelus
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. #include <stdexcept>
  18. #include <algorithm>
  19. #include <unistd.h>
  20. #include <fcntl.h>
  21. #include <core/os/fork_pipe.h>
  22. namespace rainynite {
  23. pid_t fork_pipe(FILE*& write_pipe, FILE*& read_pipe, vector<string> args) {
  24. if (args.size() < 1)
  25. throw std::invalid_argument("Empty argument list");
  26. int write_pipe_ds[2];
  27. pipe(write_pipe_ds);
  28. int read_pipe_ds[2];
  29. pipe(read_pipe_ds);
  30. auto pid = fork();
  31. if (pid == 0) {
  32. dup2(write_pipe_ds[0], STDIN_FILENO);
  33. close(write_pipe_ds[0]);
  34. close(write_pipe_ds[1]);
  35. dup2(read_pipe_ds[1], STDOUT_FILENO);
  36. dup2(read_pipe_ds[1], STDERR_FILENO);
  37. close(read_pipe_ds[0]);
  38. close(read_pipe_ds[1]);
  39. char const** c_args = new char const*[args.size()+1];
  40. std::transform(
  41. std::begin(args),
  42. std::end(args),
  43. c_args,
  44. [](auto const& s) {
  45. return s.c_str();
  46. }
  47. );
  48. c_args[args.size()] = nullptr;
  49. execv(args[0].c_str(), const_cast<char* const*>(c_args));
  50. throw std::runtime_error("execl returned");
  51. }
  52. write_pipe = fdopen(write_pipe_ds[1], "w");
  53. close(write_pipe_ds[0]);
  54. fcntl(read_pipe_ds[0], F_SETFL, O_NONBLOCK);
  55. read_pipe = fdopen(read_pipe_ds[0], "r");
  56. close(read_pipe_ds[1]);
  57. return pid;
  58. }
  59. } // namespace rainynite