From c0e6e40cc916747a0a22c2538874348cda0ef607 Mon Sep 17 00:00:00 2001 From: Elliott Hughes Date: Tue, 22 Mar 2016 20:03:48 -0700 Subject: [PATCH] Copy the good comment and warn_unused_result from ScopedFd to unique_fd. Also list all known aliases of this class to increase the chances that anyone searching for it by another name finds it anyway. Change-Id: I58ea0a5421987fb69f93cc56252a771e9c34147e --- base/include/android-base/unique_fd.h | 34 +++++++++++++++------------ 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/base/include/android-base/unique_fd.h b/base/include/android-base/unique_fd.h index d3b27cae3..97406be84 100644 --- a/base/include/android-base/unique_fd.h +++ b/base/include/android-base/unique_fd.h @@ -21,18 +21,18 @@ #include -/* Container for a file descriptor that automatically closes the descriptor as - * it goes out of scope. - * - * unique_fd ufd(open("/some/path", "r")); - * - * if (ufd.get() < 0) // invalid descriptor - * return error; - * - * // Do something useful - * - * return 0; // descriptor is closed here - */ +// Container for a file descriptor that automatically closes the descriptor as +// it goes out of scope. +// +// unique_fd ufd(open("/some/path", "r")); +// if (ufd.get() == -1) return error; +// +// // Do something useful, possibly including 'return'. +// +// return 0; // Descriptor is closed for you. +// +// unique_fd is also known as ScopedFd/ScopedFD/scoped_fd; mentioned here to help +// you find this class if you're searching for one of those names. namespace android { namespace base { @@ -44,14 +44,18 @@ class unique_fd final { ~unique_fd() { clear(); } unique_fd(unique_fd&& other) : value_(other.release()) {} - unique_fd& operator = (unique_fd&& s) { + unique_fd& operator=(unique_fd&& s) { reset(s.release()); return *this; } void reset(int new_value) { - if (value_ >= 0) + if (value_ != -1) { + // Even if close(2) fails with EINTR, the fd will have been closed. + // Using TEMP_FAILURE_RETRY will either lead to EBADF or closing someone else's fd. + // http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html close(value_); + } value_ = new_value; } @@ -61,7 +65,7 @@ class unique_fd final { int get() const { return value_; } - int release() { + int release() __attribute__((warn_unused_result)) { int ret = value_; value_ = -1; return ret;