From 050671f8b55500a11a12e7e29ac30f47039eb30a Mon Sep 17 00:00:00 2001 From: Christopher Dykes Date: Thu, 13 Jul 2017 11:50:36 -0700 Subject: [PATCH] Add support for closing a TemporaryFile early Summary: The file itself will still get removed when `TemporaryFile` is destroyed, but closing it before then allows it to be read when on Windows, because `TemporaryFile` opens the temporary file with `O_EXCL`, so Windows denies read access of the file to everything else. This is needed to fix one of the AsyncFileWriter tests on Windows. Reviewed By: simpkins Differential Revision: D5307719 fbshipit-source-id: bd65962cc3d34f382cc7b0b55dbf2659ed5ebfce --- folly/experimental/TestUtil.cpp | 9 ++++++++- folly/experimental/TestUtil.h | 1 + folly/experimental/test/TestUtilTest.cpp | 13 +++++++++++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/folly/experimental/TestUtil.cpp b/folly/experimental/TestUtil.cpp index d0f39b94..cbaa3246 100644 --- a/folly/experimental/TestUtil.cpp +++ b/folly/experimental/TestUtil.cpp @@ -74,6 +74,13 @@ TemporaryFile::TemporaryFile(StringPiece namePrefix, } } +void TemporaryFile::close() { + if (::close(fd_) == -1) { + PLOG(ERROR) << "close failed"; + } + fd_ = -1; +} + const fs::path& TemporaryFile::path() const { CHECK(scope_ != Scope::UNLINK_IMMEDIATELY); DCHECK(!path_.empty()); @@ -82,7 +89,7 @@ const fs::path& TemporaryFile::path() const { TemporaryFile::~TemporaryFile() { if (fd_ != -1 && closeOnDestruction_) { - if (close(fd_) == -1) { + if (::close(fd_) == -1) { PLOG(ERROR) << "close failed"; } } diff --git a/folly/experimental/TestUtil.h b/folly/experimental/TestUtil.h index cc110feb..2460b84b 100644 --- a/folly/experimental/TestUtil.h +++ b/folly/experimental/TestUtil.h @@ -54,6 +54,7 @@ class TemporaryFile { TemporaryFile(TemporaryFile&&) = default; TemporaryFile& operator=(TemporaryFile&&) = default; + void close(); int fd() const { return fd_; } const fs::path& path() const; diff --git a/folly/experimental/test/TestUtilTest.cpp b/folly/experimental/test/TestUtilTest.cpp index 32196ecc..72b9ccbf 100644 --- a/folly/experimental/test/TestUtilTest.cpp +++ b/folly/experimental/test/TestUtilTest.cpp @@ -53,6 +53,19 @@ TEST(TemporaryFile, Simple) { }); } +TEST(TemporaryFile, EarlyClose) { + fs::path p; + { + TemporaryFile f; + p = f.path(); + EXPECT_TRUE(fs::exists(p)); + f.close(); + EXPECT_EQ(-1, f.fd()); + EXPECT_TRUE(fs::exists(p)); + } + EXPECT_FALSE(fs::exists(p)); +} + TEST(TemporaryFile, Prefix) { TemporaryFile f("Foo"); EXPECT_TRUE(f.path().is_absolute()); -- 2.34.1