From f9bc1b057165bb5ea89acf135f7f3a90eff579ab Mon Sep 17 00:00:00 2001 From: Tianjie Xu Date: Mon, 11 Sep 2017 12:01:09 -0700 Subject: [PATCH] Add the Release function for TemporaryFiles Some tests may create a File* by calling fdopen() on the temp file's fd. We should release the ownership of fd in this case to avoid the double close. Bug: 65430057 Test: libbase unit tests pass Change-Id: I54fcce2029f9a574f53afdbdda737ee58620c73a --- base/include/android-base/test_utils.h | 4 ++++ base/test_utils.cpp | 10 +++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/base/include/android-base/test_utils.h b/base/include/android-base/test_utils.h index c0bf0c1e1..07a5edda0 100644 --- a/base/include/android-base/test_utils.h +++ b/base/include/android-base/test_utils.h @@ -26,6 +26,10 @@ class TemporaryFile { TemporaryFile(); ~TemporaryFile(); + // Release the ownership of fd, caller is reponsible for closing the + // fd or stream properly. + int release(); + int fd; char path[1024]; diff --git a/base/test_utils.cpp b/base/test_utils.cpp index 636477d36..1cfa9e66f 100644 --- a/base/test_utils.cpp +++ b/base/test_utils.cpp @@ -85,10 +85,18 @@ TemporaryFile::TemporaryFile() { } TemporaryFile::~TemporaryFile() { - close(fd); + if (fd != -1) { + close(fd); + } unlink(path); } +int TemporaryFile::release() { + int result = fd; + fd = -1; + return result; +} + void TemporaryFile::init(const std::string& tmp_dir) { snprintf(path, sizeof(path), "%s%cTemporaryFile-XXXXXX", tmp_dir.c_str(), OS_PATH_SEPARATOR);