file_descriptor.hpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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/filesystem/path.hpp>
  10. namespace boost { namespace process { namespace detail { namespace posix {
  11. struct file_descriptor
  12. {
  13. enum mode_t
  14. {
  15. read = 1,
  16. write = 2,
  17. read_write = 3
  18. };
  19. file_descriptor() = default;
  20. explicit file_descriptor(const boost::filesystem::path& p, mode_t mode = read_write)
  21. : file_descriptor(p.native(), mode)
  22. {
  23. }
  24. explicit file_descriptor(const std::string & path , mode_t mode = read_write)
  25. : file_descriptor(path.c_str(), mode) {}
  26. explicit file_descriptor(const char* path, mode_t mode = read_write)
  27. : _handle(create_file(path, mode))
  28. {
  29. }
  30. file_descriptor(const file_descriptor & ) = delete;
  31. file_descriptor(file_descriptor && ) = default;
  32. file_descriptor& operator=(const file_descriptor & ) = delete;
  33. file_descriptor& operator=(file_descriptor && ) = default;
  34. ~file_descriptor()
  35. {
  36. if (_handle != -1)
  37. ::close(_handle);
  38. }
  39. int handle() const { return _handle;}
  40. private:
  41. static int create_file(const char* name, mode_t mode )
  42. {
  43. switch(mode)
  44. {
  45. case read:
  46. return ::open(name, O_RDONLY);
  47. case write:
  48. return ::open(name, O_WRONLY | O_CREAT, 0660);
  49. case read_write:
  50. return ::open(name, O_RDWR | O_CREAT, 0660);
  51. default:
  52. return -1;
  53. }
  54. }
  55. int _handle = -1;
  56. };
  57. }}}}
  58. #endif /* BOOST_PROCESS_DETAIL_WINDOWS_FILE_DESCRIPTOR_HPP_ */