diff options
| author | Josh Gao <jmgao@google.com> | 2018-09-04 11:05:08 -0700 |
|---|---|---|
| committer | Josh Gao <jmgao@google.com> | 2018-09-04 13:13:50 -0700 |
| commit | a3c868879c7cd7f52b206246d9839b60cc3dbeb9 (patch) | |
| tree | 0df8485aa4905ee0e085902c39e1805b5dc57ab2 /base | |
| parent | ebb631b0a32556cdeda70d3bf9e6f6460667b42f (diff) | |
| download | system_core-a3c868879c7cd7f52b206246d9839b60cc3dbeb9.tar.gz system_core-a3c868879c7cd7f52b206246d9839b60cc3dbeb9.tar.bz2 system_core-a3c868879c7cd7f52b206246d9839b60cc3dbeb9.zip | |
libbase: add Fdopen that takes a unique_fd.
Using fdopen with unique_fd correctly is more annoying than it should
be, because fdopen doesn't close the file descriptor received upon
failure, which means you have to something like the following:
unique_fd ufd = ...;
int fd = ufd.release();
FILE* file = fdopen(fd, "...");
if (!file) {
close(fd);
return;
}
Add an android::base::Fdopen that does that dance for you.
Bug: http://b/113880863
Test: treehugger
Change-Id: I6325acf1ff06484005c1053fe09672c5eeeecaa1
Diffstat (limited to 'base')
| -rw-r--r-- | base/include/android-base/unique_fd.h | 12 |
1 files changed, 12 insertions, 0 deletions
diff --git a/base/include/android-base/unique_fd.h b/base/include/android-base/unique_fd.h index c6936f137..71025adc2 100644 --- a/base/include/android-base/unique_fd.h +++ b/base/include/android-base/unique_fd.h @@ -22,6 +22,7 @@ #include <sys/socket.h> #endif +#include <stdio.h> #include <sys/types.h> #include <unistd.h> @@ -199,6 +200,17 @@ inline bool Socketpair(int type, unique_fd_impl<Closer>* left, unique_fd_impl<Cl return Socketpair(AF_UNIX, type, 0, left, right); } +// Using fdopen with unique_fd correctly is more annoying than it should be, +// because fdopen doesn't close the file descriptor received upon failure. +inline FILE* Fdopen(unique_fd&& ufd, const char* mode) { + int fd = ufd.release(); + FILE* file = fdopen(fd, mode); + if (!file) { + close(fd); + } + return file; +} + #endif // !defined(_WIN32) } // namespace base |
