scoped_fd.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /* scoped_fd, automatically close a file descriptor
  2. Copyright (C) 2018-2022 Free Software Foundation, Inc.
  3. This file is part of GDB.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  14. #ifndef COMMON_SCOPED_FD_H
  15. #define COMMON_SCOPED_FD_H
  16. #include <unistd.h>
  17. #include "gdb_file.h"
  18. /* A smart-pointer-like class to automatically close a file descriptor. */
  19. class scoped_fd
  20. {
  21. public:
  22. explicit scoped_fd (int fd = -1) noexcept : m_fd (fd) {}
  23. scoped_fd (scoped_fd &&other) noexcept
  24. : m_fd (other.m_fd)
  25. {
  26. other.m_fd = -1;
  27. }
  28. ~scoped_fd ()
  29. {
  30. if (m_fd >= 0)
  31. close (m_fd);
  32. }
  33. scoped_fd &operator= (scoped_fd &&other)
  34. {
  35. if (m_fd != other.m_fd)
  36. {
  37. if (m_fd >= 0)
  38. close (m_fd);
  39. m_fd = other.m_fd;
  40. other.m_fd = -1;
  41. }
  42. return *this;
  43. }
  44. DISABLE_COPY_AND_ASSIGN (scoped_fd);
  45. ATTRIBUTE_UNUSED_RESULT int release () noexcept
  46. {
  47. int fd = m_fd;
  48. m_fd = -1;
  49. return fd;
  50. }
  51. /* Like release, but return a gdb_file_up that owns the file
  52. descriptor. On success, this scoped_fd will be released. On
  53. failure, return NULL and leave this scoped_fd in possession of
  54. the fd. */
  55. gdb_file_up to_file (const char *mode) noexcept
  56. {
  57. gdb_file_up result (fdopen (m_fd, mode));
  58. if (result != nullptr)
  59. m_fd = -1;
  60. return result;
  61. }
  62. int get () const noexcept
  63. {
  64. return m_fd;
  65. }
  66. private:
  67. int m_fd;
  68. };
  69. #endif /* COMMON_SCOPED_FD_H */