fifotest.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. #include <cstdio>
  5. #include <cstdlib>
  6. #include <unistd.h>
  7. #include <sys/types.h>
  8. #include <sys/stat.h>
  9. #include <fcntl.h>
  10. const char* PIPE_NAME = "/tmp/bash_pipe";
  11. int main()
  12. {
  13. mkfifo(PIPE_NAME, 0666);
  14. while (true)
  15. {
  16. int pipe_fd = open(PIPE_NAME, O_RDONLY);
  17. if (pipe_fd == -1)
  18. {
  19. perror("open");
  20. exit(EXIT_FAILURE);
  21. }
  22. std::string command;
  23. char buffer[128];
  24. ssize_t bytes_read;
  25. while ((bytes_read = read(pipe_fd, buffer, sizeof(buffer))) > 0)
  26. {
  27. command.append(buffer, bytes_read);
  28. }
  29. close(pipe_fd);
  30. int pipe_to_child[2];
  31. int pipe_from_child[2];
  32. if (pipe(pipe_to_child) == -1 || pipe(pipe_from_child) == -1)
  33. {
  34. std::cerr << "Failed to create pipes\n";
  35. exit(EXIT_FAILURE);
  36. }
  37. pid_t pid = fork();
  38. if (pid < 0)
  39. {
  40. std::cerr << "Fork failed\n";
  41. exit(EXIT_FAILURE);
  42. }
  43. else if (pid == 0)
  44. {
  45. close(pipe_to_child[1]);
  46. close(pipe_from_child[0]);
  47. dup2(pipe_to_child[0], STDIN_FILENO);
  48. dup2(pipe_from_child[1], STDOUT_FILENO);
  49. execl("/bin/bash", "/bin/bash", "-i", nullptr);
  50. perror("exec");
  51. exit(EXIT_FAILURE);
  52. }
  53. else
  54. {
  55. close(pipe_to_child[0]);
  56. close(pipe_from_child[1]);
  57. write(pipe_to_child[1], command.c_str(), command.size());
  58. close(pipe_to_child[1]);
  59. char output_buffer[128];
  60. ssize_t output_bytes_read;
  61. std::ofstream pipe_out(PIPE_NAME, std::ofstream::trunc);
  62. while ((output_bytes_read =
  63. read(pipe_from_child[0], output_buffer, sizeof(output_buffer))) > 0)
  64. {
  65. pipe_out.write(output_buffer, output_bytes_read);
  66. }
  67. close(pipe_from_child[0]);
  68. pipe_out.close();
  69. }
  70. }
  71. unlink(PIPE_NAME);
  72. return 0;
  73. }