Commit | Line | Data |
---|---|---|
ea4a0888 MM |
1 | /* scoped_fd, automatically close a file descriptor |
2 | ||
3 | Copyright (C) 2018 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 SCOPED_FD_H | |
21 | #define SCOPED_FD_H | |
22 | ||
ea4a0888 MM |
23 | #include <unistd.h> |
24 | ||
25 | /* A smart-pointer-like class to automatically close a file descriptor. */ | |
26 | ||
27 | class scoped_fd | |
28 | { | |
29 | public: | |
30 | explicit scoped_fd (int fd = -1) noexcept : m_fd (fd) {} | |
31 | ~scoped_fd () | |
32 | { | |
33 | if (m_fd >= 0) | |
34 | close (m_fd); | |
35 | } | |
36 | ||
37 | DISABLE_COPY_AND_ASSIGN (scoped_fd); | |
38 | ||
39 | int release () noexcept | |
40 | { | |
41 | int fd = m_fd; | |
42 | m_fd = -1; | |
43 | return fd; | |
44 | } | |
45 | ||
46 | int get () const noexcept | |
47 | { | |
48 | return m_fd; | |
49 | } | |
50 | ||
51 | private: | |
52 | int m_fd; | |
53 | }; | |
54 | ||
ea4a0888 | 55 | #endif /* SCOPED_FD_H */ |