tc_fifo.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /**
  2. * Tencent is pleased to support the open source community by making Tars available.
  3. *
  4. * Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved.
  5. *
  6. * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
  7. * in compliance with the License. You may obtain a copy of the License at
  8. *
  9. * https://opensource.org/licenses/BSD-3-Clause
  10. *
  11. * Unless required by applicable law or agreed to in writing, software distributed
  12. * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  13. * CONDITIONS OF ANY KIND, either express or implied. See the License for the
  14. * specific language governing permissions and limitations under the License.
  15. */
  16. #if TARGET_PLATFORM_LINUX || TARGET_PLATFORM_IOS
  17. #include <sys/types.h>
  18. #include <sys/stat.h>
  19. #include <unistd.h>
  20. #include <errno.h>
  21. #include <fcntl.h>
  22. #include "util/tc_fifo.h"
  23. namespace tars
  24. {
  25. ///////////////////////////////////////////////////////////////////////////////////////////////////
  26. //
  27. TC_Fifo::TC_Fifo(bool bOwner) : _bOwner(bOwner), _enRW(EM_READ), _fd(-1)
  28. {
  29. }
  30. TC_Fifo::~TC_Fifo()
  31. {
  32. if (_bOwner) close();
  33. }
  34. void TC_Fifo::close()
  35. {
  36. if (_fd >= 0) ::close(_fd);
  37. _fd = -1;
  38. }
  39. int TC_Fifo::open(const std::string & sPathName, ENUM_RW_SET enRW, mode_t mode)
  40. {
  41. _enRW = enRW;
  42. _sPathName = sPathName;
  43. if (_enRW != EM_READ && _enRW != EM_WRITE)
  44. {
  45. return -1;
  46. }
  47. if (::mkfifo(_sPathName.c_str(), mode) == -1 && errno != EEXIST)
  48. {
  49. return -1;
  50. }
  51. if (_enRW == EM_READ && (_fd = ::open(_sPathName.c_str(), O_NONBLOCK|O_RDONLY, 0664)) < 0)
  52. {
  53. return -1;
  54. }
  55. if (_enRW == EM_WRITE && (_fd = ::open(_sPathName.c_str(), O_NONBLOCK|O_WRONLY, 0664)) < 0)
  56. {
  57. return -1;
  58. }
  59. return 0;
  60. }
  61. int TC_Fifo::read(char * szBuff, const size_t sizeMax)
  62. {
  63. return ::read(_fd, szBuff, sizeMax);
  64. }
  65. int TC_Fifo::write(const char * szBuff, const size_t sizeBuffLen)
  66. {
  67. if (sizeBuffLen == 0) return 0;
  68. return ::write(_fd, szBuff, sizeBuffLen);
  69. }
  70. }
  71. #endif