| /* -*- Mode: C++; tab-width: 8; c-basic-offset: 2; indent-tabs-mode: nil; -*- */ |
| * RAII helper to open a file and then close the fd when the helper |
| explicit ScopedFd(int fd) : fd(fd) {} |
| ScopedFd(const char* pathname, int flags, mode_t mode = 0) |
| : fd(open(pathname, flags, mode)) {} |
| ScopedFd(ScopedFd&& other) : fd(other.fd) { other.fd = -1; } |
| ScopedFd& operator=(ScopedFd&& other) { |
| operator int() const { return get(); } |
| int get() const { return fd; } |
| bool is_open() const { return fd >= 0; } |
| // With EINTR/EIO, it is unspecified whether fd will be |
| // closed, but on Linux, it is always removed from the FD |
| // table, so the close was successful for our purposes. |
| if (err != 0 && err != -EINTR && err != -EIO) { |
| FATAL() << "Unexpected error while closing fd " << fd; |
| static ScopedFd openat(const ScopedFd &dir, const char* pathname, |
| int flags, mode_t mode = 0) { |
| return ScopedFd(::openat(dir.get(), pathname, flags, mode)); |