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 #include "JNIHelp.h"  // for DISALLOW_COPY_AND_ASSIGN.
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 final {
27 public:
ScopedFd(int fd)28     explicit ScopedFd(int fd) : fd_(fd) {
29     }
ScopedFd()30     ScopedFd() : ScopedFd(-1) {}
31 
~ScopedFd()32     ~ScopedFd() {
33       reset();
34     }
35 
ScopedFd(ScopedFd && other)36     ScopedFd(ScopedFd&& other) : fd_(other.release()) {}
37     ScopedFd& operator = (ScopedFd&& s) {
38         reset(s.release());
39         return *this;
40     }
41 
get()42     int get() const {
43         return fd_;
44     }
45 
release()46     int release() __attribute__((warn_unused_result)) {
47         int localFd = fd_;
48         fd_ = -1;
49         return localFd;
50     }
51 
52     void reset(int new_fd = -1) {
53       if (fd_ != -1) {
54         // Even if close(2) fails with EINTR, the fd will have been closed.
55         // Using TEMP_FAILURE_RETRY will either lead to EBADF or closing someone else's fd.
56         // http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
57         close(fd_);
58       }
59       fd_ = new_fd;
60     }
61 
62 private:
63     int fd_;
64 
65     DISALLOW_COPY_AND_ASSIGN(ScopedFd);
66 };
67 
68 #endif  // SCOPED_FD_H_included
69