OLD | NEW |
(Empty) | |
| 1 /* |
| 2 * Copyright (C) 2009 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 SCOPED_FD_H_included |
| 18 #define SCOPED_FD_H_included |
| 19 |
| 20 #include <unistd.h> |
| 21 |
| 22 // Local definition of DISALLOW_COPY_AND_ASSIGN, avoids depending on base. |
| 23 #define DISALLOW_COPY_AND_ASSIGN(TypeName) \ |
| 24 TypeName(const TypeName&); \ |
| 25 void operator=(const TypeName&) |
| 26 |
| 27 // A smart pointer that closes the given fd on going out of scope. |
| 28 // Use this when the fd is incidental to the purpose of your function, |
| 29 // but needs to be cleaned up on exit. |
| 30 class ScopedFd { |
| 31 public: |
| 32 explicit ScopedFd(int fd) : fd_(fd) { |
| 33 } |
| 34 |
| 35 ~ScopedFd() { |
| 36 reset(); |
| 37 } |
| 38 |
| 39 int get() const { |
| 40 return fd_; |
| 41 } |
| 42 |
| 43 int release() __attribute__((warn_unused_result)) { |
| 44 int localFd = fd_; |
| 45 fd_ = -1; |
| 46 return localFd; |
| 47 } |
| 48 |
| 49 void reset(int new_fd = -1) { |
| 50 if (fd_ != -1) { |
| 51 TEMP_FAILURE_RETRY(close(fd_)); |
| 52 } |
| 53 fd_ = new_fd; |
| 54 } |
| 55 |
| 56 private: |
| 57 int fd_; |
| 58 |
| 59 DISALLOW_COPY_AND_ASSIGN(ScopedFd); |
| 60 }; |
| 61 |
| 62 #endif // SCOPED_FD_H_included |
OLD | NEW |