Commit 050671f8 authored by Christopher Dykes's avatar Christopher Dykes Committed by Facebook Github Bot

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
parent 6ecf60a9
......@@ -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";
}
}
......
......@@ -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;
......
......@@ -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());
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment