Casey Dahlin | 1a0849a | 2015-11-12 14:52:13 -0800 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2015 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #ifndef ANDROID_BASE_UNIQUE_FD_H |
| 18 | #define ANDROID_BASE_UNIQUE_FD_H |
| 19 | |
| 20 | #include <unistd.h> |
| 21 | |
Elliott Hughes | b635162 | 2015-12-04 22:00:26 -0800 | [diff] [blame] | 22 | #include <android-base/macros.h> |
Casey Dahlin | 1a0849a | 2015-11-12 14:52:13 -0800 | [diff] [blame] | 23 | |
| 24 | /* Container for a file descriptor that automatically closes the descriptor as |
| 25 | * it goes out of scope. |
| 26 | * |
| 27 | * unique_fd ufd(open("/some/path", "r")); |
| 28 | * |
| 29 | * if (ufd.get() < 0) // invalid descriptor |
| 30 | * return error; |
| 31 | * |
| 32 | * // Do something useful |
| 33 | * |
| 34 | * return 0; // descriptor is closed here |
| 35 | */ |
| 36 | namespace android { |
| 37 | namespace base { |
| 38 | |
| 39 | class unique_fd final { |
| 40 | public: |
| 41 | unique_fd() : value_(-1) {} |
| 42 | |
| 43 | explicit unique_fd(int value) : value_(value) {} |
| 44 | ~unique_fd() { clear(); } |
| 45 | |
| 46 | unique_fd(unique_fd&& other) : value_(other.release()) {} |
| 47 | unique_fd& operator = (unique_fd&& s) { |
| 48 | reset(s.release()); |
| 49 | return *this; |
| 50 | } |
| 51 | |
| 52 | void reset(int new_value) { |
| 53 | if (value_ >= 0) |
| 54 | close(value_); |
| 55 | value_ = new_value; |
| 56 | } |
| 57 | |
| 58 | void clear() { |
| 59 | reset(-1); |
| 60 | } |
| 61 | |
| 62 | int get() const { return value_; } |
| 63 | |
| 64 | int release() { |
| 65 | int ret = value_; |
| 66 | value_ = -1; |
| 67 | return ret; |
| 68 | } |
| 69 | |
| 70 | private: |
| 71 | int value_; |
| 72 | |
| 73 | DISALLOW_COPY_AND_ASSIGN(unique_fd); |
| 74 | }; |
| 75 | |
| 76 | } // namespace base |
| 77 | } // namespace android |
| 78 | |
| 79 | #endif // ANDROID_BASE_UNIQUE_FD_H |