Home | History | Annotate | Download | only in files
      1 // Copyright 2014 The Android Open Source Project
      2 //
      3 // This software is licensed under the terms of the GNU General Public
      4 // License version 2, as published by the Free Software Foundation, and
      5 // may be copied, distributed, and modified under those terms.
      6 //
      7 // This program is distributed in the hope that it will be useful,
      8 // but WITHOUT ANY WARRANTY; without even the implied warranty of
      9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     10 // GNU General Public License for more details.
     11 
     12 #ifndef ANDROID_BASE_SCOPED_FD_H
     13 #define ANDROID_BASE_SCOPED_FD_H
     14 
     15 #include "android/base/Compiler.h"
     16 
     17 #include <errno.h>
     18 #include <unistd.h>
     19 
     20 namespace android {
     21 namespace base {
     22 
     23 // Helper class to hold an integer file descriptor, and have the 'close'
     24 // function called automatically on scope exit, unless the 'release'
     25 // method was called previously.
     26 class ScopedFd {
     27 public:
     28     // Default constructor will hold an invalid descriptor.
     29     ScopedFd() : fd_(-1) {}
     30 
     31     // Constructor takes ownership of |fd|.
     32     explicit ScopedFd(int fd) : fd_(fd) {}
     33 
     34     // Destructor calls close().
     35     ~ScopedFd() { close(); }
     36 
     37     // Return the file descriptor value, does _not_ transfer ownership.
     38     int get() const { return fd_; }
     39 
     40     // Return the file descriptor value, transfers ownership to the caller.
     41     int release() {
     42         int fd = fd_;
     43         fd_ = -1;
     44         return fd;
     45     }
     46 
     47     // Return true iff the file descriptor is valid.
     48     bool valid() const { return fd_ >= 0; }
     49 
     50     // Close the file descriptor (and make the wrapped value invalid).
     51     void close() {
     52         if (fd_ != -1) {
     53             int save_errno = errno;
     54             ::close(fd_);
     55             fd_ = -1;
     56             errno = save_errno;
     57         }
     58     }
     59 
     60     // Swap two ScopedFd instances.
     61     void swap(ScopedFd* other) {
     62         int fd = fd_;
     63         fd_ = other->fd_;
     64         other->fd_ = fd;
     65     }
     66 
     67 private:
     68     DISALLOW_COPY_AND_ASSIGN(ScopedFd);
     69 
     70     int fd_;
     71 };
     72 
     73 }  // namespace base
     74 }  // namespace android
     75 
     76 #endif  // ANDROID_BASE_SCOPED_FD_H
     77