file_descriptor.hpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright (c) 2016 Klemens D. Morgenstern
  2. //
  3. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  4. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5. #ifndef BOOST_PROCESS_DETAIL_POSIX_FILE_DESCRIPTOR_HPP_
  6. #define BOOST_PROCESS_DETAIL_POSIX_FILE_DESCRIPTOR_HPP_
  7. #include <fcntl.h>
  8. #include <string>
  9. #include <boost/process/v1/filesystem.hpp>
  10. #include <boost/core/exchange.hpp>
  11. namespace boost { namespace process { BOOST_PROCESS_V1_INLINE namespace v1 { namespace detail { namespace posix {
  12. struct file_descriptor
  13. {
  14. enum mode_t
  15. {
  16. read = 1,
  17. write = 2,
  18. read_write = 3
  19. };
  20. file_descriptor() = default;
  21. explicit file_descriptor(const boost::process::v1::filesystem::path& p, mode_t mode = read_write)
  22. : file_descriptor(p.native(), mode)
  23. {
  24. }
  25. explicit file_descriptor(const std::string & path , mode_t mode = read_write)
  26. : file_descriptor(path.c_str(), mode) {}
  27. explicit file_descriptor(const char* path, mode_t mode = read_write)
  28. : _handle(create_file(path, mode))
  29. {
  30. }
  31. file_descriptor(const file_descriptor & ) = delete;
  32. file_descriptor(file_descriptor &&other)
  33. : _handle(boost::exchange(other._handle, -1))
  34. {
  35. }
  36. file_descriptor& operator=(const file_descriptor & ) = delete;
  37. file_descriptor& operator=(file_descriptor &&other)
  38. {
  39. if (this != &other)
  40. {
  41. if (_handle != -1)
  42. ::close(_handle);
  43. _handle = boost::exchange(other._handle, -1);
  44. }
  45. return *this;
  46. }
  47. ~file_descriptor()
  48. {
  49. if (_handle != -1)
  50. ::close(_handle);
  51. }
  52. int handle() const { return _handle;}
  53. private:
  54. static int create_file(const char* name, mode_t mode )
  55. {
  56. switch(mode)
  57. {
  58. case read:
  59. return ::open(name, O_RDONLY);
  60. case write:
  61. return ::open(name, O_WRONLY | O_CREAT, 0660);
  62. case read_write:
  63. return ::open(name, O_RDWR | O_CREAT, 0660);
  64. default:
  65. return -1;
  66. }
  67. }
  68. int _handle = -1;
  69. };
  70. }}}}}
  71. #endif /* BOOST_PROCESS_DETAIL_WINDOWS_FILE_DESCRIPTOR_HPP_ */