Summary: It's convenient to get back the fd, similar to unique_ptr::release().
Test Plan: unittest
Reviewed By: tudorb@fb.com
FB internal diff:
D1080426
File::File(int fd, bool ownsFd)
: fd_(fd)
- , ownsFd_(ownsFd)
-{}
+ , ownsFd_(ownsFd) {
+ CHECK_GE(fd, -1) << "fd must be -1 or non-negative";
+ CHECK(fd != -1 || !ownsFd) << "cannot own -1";
+}
File::File(const char* name, int flags, mode_t mode)
: fd_(::open(name, flags, mode))
File::File(File&& other)
: fd_(other.fd_)
, ownsFd_(other.ownsFd_) {
-
other.release();
}
return File(fd, true);
}
-void File::release() {
+int File::release() {
+ int released = fd_;
fd_ = -1;
ownsFd_ = false;
+ return released;
}
void File::swap(File& other) {
}
File File::dup() const {
- if (fd_ >= 0) {
+ if (fd_ != -1) {
int fd = ::dup(fd_);
checkUnixError(fd, "dup() failed");
* Returns 'true' iff the file was successfully opened.
*/
explicit operator bool() const {
- return fd_ >= 0;
+ return fd_ != -1;
}
/**
bool closeNoThrow();
/**
- * Releases the file descriptor; no longer owned by this File.
+ * Returns and releases the file descriptor; no longer owned by this File.
+ * Returns -1 if the File object didn't wrap a file.
*/
- void release();
+ int release();
/**
* Swap this File with another.
::close(p[0]);
}
+TEST(File, Release) {
+ File in(STDOUT_FILENO, false);
+ CHECK_EQ(STDOUT_FILENO, in.release());
+ CHECK_EQ(-1, in.release());
+}
+
#define EXPECT_CONTAINS(haystack, needle) \
EXPECT_NE(::std::string::npos, ::folly::StringPiece(haystack).find(needle)) \
<< "Haystack: '" << haystack << "'\nNeedle: '" << needle << "'";