Commit | Line | Data |
---|---|---|
ea4a0888 MM |
1 | /* scoped_fd, automatically close a file descriptor |
2 | ||
b811d2c2 | 3 | Copyright (C) 2018-2020 Free Software Foundation, Inc. |
ea4a0888 MM |
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 | ||
1a5c2598 TT |
20 | #ifndef COMMON_SCOPED_FD_H |
21 | #define COMMON_SCOPED_FD_H | |
ea4a0888 | 22 | |
ea4a0888 | 23 | #include <unistd.h> |
36033ef5 | 24 | #include "filestuff.h" |
ea4a0888 MM |
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) {} | |
2179fbc3 | 32 | |
0fa7617d | 33 | scoped_fd (scoped_fd &&other) noexcept |
2179fbc3 TT |
34 | : m_fd (other.m_fd) |
35 | { | |
36 | other.m_fd = -1; | |
37 | } | |
38 | ||
ea4a0888 MM |
39 | ~scoped_fd () |
40 | { | |
41 | if (m_fd >= 0) | |
42 | close (m_fd); | |
43 | } | |
44 | ||
2179fbc3 TT |
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 | ||
ea4a0888 MM |
57 | DISABLE_COPY_AND_ASSIGN (scoped_fd); |
58 | ||
3cabd438 | 59 | ATTRIBUTE_UNUSED_RESULT int release () noexcept |
ea4a0888 MM |
60 | { |
61 | int fd = m_fd; | |
62 | m_fd = -1; | |
63 | return fd; | |
64 | } | |
65 | ||
36033ef5 TT |
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 | ||
ea4a0888 MM |
78 | int get () const noexcept |
79 | { | |
80 | return m_fd; | |
81 | } | |
82 | ||
83 | private: | |
84 | int m_fd; | |
85 | }; | |
86 | ||
1a5c2598 | 87 | #endif /* COMMON_SCOPED_FD_H */ |