| Dmitriy Ivanov | 04dc91a | 2014-07-01 14:10:16 -0700 | [diff] [blame] | 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 | 
|  | 18 | #define SCOPED_FD_H | 
|  | 19 |  | 
|  | 20 | #include <unistd.h> | 
|  | 21 | #include "bionic_macros.h" | 
|  | 22 |  | 
|  | 23 | // A smart pointer that closes the given fd on going out of scope. | 
|  | 24 | // Use this when the fd is incidental to the purpose of your function, | 
|  | 25 | // but needs to be cleaned up on exit. | 
|  | 26 | class ScopedFd { | 
|  | 27 | public: | 
|  | 28 | explicit ScopedFd(int fd) : fd(fd) { | 
|  | 29 | } | 
|  | 30 |  | 
|  | 31 | ~ScopedFd() { | 
|  | 32 | reset(); | 
|  | 33 | } | 
|  | 34 |  | 
|  | 35 | int get() const { | 
|  | 36 | return fd; | 
|  | 37 | } | 
|  | 38 |  | 
|  | 39 | int release() __attribute__((warn_unused_result)) { | 
|  | 40 | int localFd = fd; | 
|  | 41 | fd = -1; | 
|  | 42 | return localFd; | 
|  | 43 | } | 
|  | 44 |  | 
|  | 45 | void reset(int new_fd = -1) { | 
|  | 46 | if (fd != -1) { | 
|  | 47 | TEMP_FAILURE_RETRY(close(fd)); | 
|  | 48 | } | 
|  | 49 | fd = new_fd; | 
|  | 50 | } | 
|  | 51 |  | 
|  | 52 | private: | 
|  | 53 | int fd; | 
|  | 54 |  | 
|  | 55 | // Disallow copy and assignment. | 
|  | 56 | DISALLOW_COPY_AND_ASSIGN(ScopedFd); | 
|  | 57 | }; | 
|  | 58 |  | 
|  | 59 | #endif  // SCOPED_FD_H |