libbase: add Fdopendir that takes a unique_fd.

Using fdopendir with unique_fd correctly is more annoying than it
should be, because fdopendir doesn't close the file descriptor
received upon failure.

Add an android::base::Fdopendir that does that handles the failure
case.

Bug: 118818285
Test: treehugger
Change-Id: I5dbbe0eb82242bc7716f84735ffc7644febcfd65
This commit is contained in:
Mathieu Chartier 2018-11-02 08:05:31 -07:00
parent 6d7c8fcc92
commit 1666bafa70

View file

@ -19,6 +19,7 @@
#include <fcntl.h>
#if !defined(_WIN32)
#include <dirent.h>
#include <sys/socket.h>
#endif
@ -211,6 +212,17 @@ inline FILE* Fdopen(unique_fd&& ufd, const char* mode) {
return file;
}
// Using fdopendir with unique_fd correctly is more annoying than it should be,
// because fdopen doesn't close the file descriptor received upon failure.
inline DIR* Fdopendir(unique_fd&& ufd) {
int fd = ufd.release();
DIR* dir = fdopendir(fd);
if (dir == nullptr) {
close(fd);
}
return dir;
}
#endif // !defined(_WIN32)
} // namespace base