pipe.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // Name: wx/unix/pipe.h
  3. // Purpose: wxPipe class
  4. // Author: Vadim Zeitlin
  5. // Modified by:
  6. // Created: 24.06.2003 (extracted from src/unix/utilsunx.cpp)
  7. // Copyright: (c) 2003 Vadim Zeitlin <vadim@wxwidgets.org>
  8. // Licence: wxWindows licence
  9. ///////////////////////////////////////////////////////////////////////////////
  10. #ifndef _WX_UNIX_PIPE_H_
  11. #define _WX_UNIX_PIPE_H_
  12. #include <unistd.h>
  13. #include <fcntl.h>
  14. #include "wx/log.h"
  15. #include "wx/intl.h"
  16. // ----------------------------------------------------------------------------
  17. // wxPipe: this class encapsulates pipe() system call
  18. // ----------------------------------------------------------------------------
  19. class wxPipe
  20. {
  21. public:
  22. // the symbolic names for the pipe ends
  23. enum Direction
  24. {
  25. Read,
  26. Write
  27. };
  28. enum
  29. {
  30. INVALID_FD = -1
  31. };
  32. // default ctor doesn't do anything
  33. wxPipe() { m_fds[Read] = m_fds[Write] = INVALID_FD; }
  34. // create the pipe, return TRUE if ok, FALSE on error
  35. bool Create()
  36. {
  37. if ( pipe(m_fds) == -1 )
  38. {
  39. wxLogSysError(wxGetTranslation("Pipe creation failed"));
  40. return false;
  41. }
  42. return true;
  43. }
  44. // switch the given end of the pipe to non-blocking IO
  45. bool MakeNonBlocking(Direction which)
  46. {
  47. const int flags = fcntl(m_fds[which], F_GETFL, 0);
  48. if ( flags == -1 )
  49. return false;
  50. return fcntl(m_fds[which], F_SETFL, flags | O_NONBLOCK) == 0;
  51. }
  52. // return TRUE if we were created successfully
  53. bool IsOk() const { return m_fds[Read] != INVALID_FD; }
  54. // return the descriptor for one of the pipe ends
  55. int operator[](Direction which) const { return m_fds[which]; }
  56. // detach a descriptor, meaning that the pipe dtor won't close it, and
  57. // return it
  58. int Detach(Direction which)
  59. {
  60. int fd = m_fds[which];
  61. m_fds[which] = INVALID_FD;
  62. return fd;
  63. }
  64. // close the pipe descriptors
  65. void Close()
  66. {
  67. for ( size_t n = 0; n < WXSIZEOF(m_fds); n++ )
  68. {
  69. if ( m_fds[n] != INVALID_FD )
  70. {
  71. close(m_fds[n]);
  72. m_fds[n] = INVALID_FD;
  73. }
  74. }
  75. }
  76. // dtor closes the pipe descriptors
  77. ~wxPipe() { Close(); }
  78. private:
  79. int m_fds[2];
  80. };
  81. #endif // _WX_UNIX_PIPE_H_