pipe.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Warray-bounds" // need because of bug in gcc4.9.2
  5. #endif
  6. #include "defaults.h"
  7. #include "file.h"
  8. #include <util/generic/ptr.h>
  9. #include <util/network/pair.h>
  10. #include <util/generic/noncopyable.h>
  11. using PIPEHANDLE = SOCKET;
  12. #define INVALID_PIPEHANDLE INVALID_SOCKET
  13. /// Pipe-like object: pipe on POSIX and socket on windows
  14. class TPipeHandle: public TNonCopyable {
  15. public:
  16. inline TPipeHandle() noexcept
  17. : Fd_(INVALID_PIPEHANDLE)
  18. {
  19. }
  20. inline TPipeHandle(PIPEHANDLE fd) noexcept
  21. : Fd_(fd)
  22. {
  23. }
  24. inline ~TPipeHandle() {
  25. Close();
  26. }
  27. bool Close() noexcept;
  28. inline PIPEHANDLE Release() noexcept {
  29. PIPEHANDLE ret = Fd_;
  30. Fd_ = INVALID_PIPEHANDLE;
  31. return ret;
  32. }
  33. inline void Swap(TPipeHandle& r) noexcept {
  34. DoSwap(Fd_, r.Fd_);
  35. }
  36. inline operator PIPEHANDLE() const noexcept {
  37. return Fd_;
  38. }
  39. inline bool IsOpen() const noexcept {
  40. return Fd_ != INVALID_PIPEHANDLE;
  41. }
  42. ssize_t Read(void* buffer, size_t byteCount) const noexcept;
  43. ssize_t Write(const void* buffer, size_t byteCount) const noexcept;
  44. // Only CloseOnExec is supported
  45. static void Pipe(TPipeHandle& reader, TPipeHandle& writer, EOpenMode mode = 0);
  46. private:
  47. PIPEHANDLE Fd_;
  48. };
  49. class TPipe {
  50. public:
  51. TPipe();
  52. /// Takes ownership of handle, so closes it when the last holder of descriptor dies.
  53. explicit TPipe(PIPEHANDLE fd);
  54. ~TPipe();
  55. void Close();
  56. bool IsOpen() const noexcept;
  57. PIPEHANDLE GetHandle() const noexcept;
  58. size_t Read(void* buf, size_t len) const;
  59. size_t Write(const void* buf, size_t len) const;
  60. // Only CloseOnExec is supported
  61. static void Pipe(TPipe& reader, TPipe& writer, EOpenMode mode = 0);
  62. private:
  63. class TImpl;
  64. using TImplRef = TSimpleIntrusivePtr<TImpl>;
  65. TImplRef Impl_;
  66. };
  67. #ifdef __GNUC__
  68. #pragma GCC diagnostic pop
  69. #endif