/src/brpc/src/butil/fd_guard.h
Line | Count | Source |
1 | | // Licensed to the Apache Software Foundation (ASF) under one |
2 | | // or more contributor license agreements. See the NOTICE file |
3 | | // distributed with this work for additional information |
4 | | // regarding copyright ownership. The ASF licenses this file |
5 | | // to you under the Apache License, Version 2.0 (the |
6 | | // "License"); you may not use this file except in compliance |
7 | | // with the License. You may obtain a copy of the License at |
8 | | // |
9 | | // http://www.apache.org/licenses/LICENSE-2.0 |
10 | | // |
11 | | // Unless required by applicable law or agreed to in writing, |
12 | | // software distributed under the License is distributed on an |
13 | | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
14 | | // KIND, either express or implied. See the License for the |
15 | | // specific language governing permissions and limitations |
16 | | // under the License. |
17 | | |
18 | | // Date: Mon. Nov 7 14:47:36 CST 2011 |
19 | | |
20 | | #ifndef BUTIL_FD_GUARD_H |
21 | | #define BUTIL_FD_GUARD_H |
22 | | |
23 | | #include <unistd.h> // close() |
24 | | |
25 | | namespace butil { |
26 | | |
27 | | // RAII file descriptor. |
28 | | // |
29 | | // Example: |
30 | | // fd_guard fd1(open(...)); |
31 | | // if (fd1 < 0) { |
32 | | // printf("Fail to open\n"); |
33 | | // return -1; |
34 | | // } |
35 | | // if (another-error-happened) { |
36 | | // printf("Fail to do sth\n"); |
37 | | // return -1; // *** closing fd1 automatically *** |
38 | | // } |
39 | | class fd_guard { |
40 | | public: |
41 | 0 | fd_guard() : _fd(-1) {} |
42 | 0 | explicit fd_guard(int fd) : _fd(fd) {} |
43 | | |
44 | 0 | ~fd_guard() { |
45 | 0 | if (_fd >= 0) { |
46 | 0 | ::close(_fd); |
47 | 0 | _fd = -1; |
48 | 0 | } |
49 | 0 | } |
50 | | |
51 | | // Close current fd and replace with another fd |
52 | 0 | void reset(int fd) { |
53 | 0 | if (_fd >= 0) { |
54 | 0 | ::close(_fd); |
55 | 0 | _fd = -1; |
56 | 0 | } |
57 | 0 | _fd = fd; |
58 | 0 | } |
59 | | |
60 | | // Set internal fd to -1 and return the value before set. |
61 | 0 | int release() { |
62 | 0 | const int prev_fd = _fd; |
63 | 0 | _fd = -1; |
64 | 0 | return prev_fd; |
65 | 0 | } |
66 | | |
67 | 0 | operator int() const { return _fd; } |
68 | | |
69 | | private: |
70 | | // Copying this makes no sense. |
71 | | fd_guard(const fd_guard&); |
72 | | void operator=(const fd_guard&); |
73 | | |
74 | | int _fd; |
75 | | }; |
76 | | |
77 | | } // namespace butil |
78 | | |
79 | | #endif // BUTIL_FD_GUARD_H |