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