fish-shell/src/fds.h
ridiculousfish be9375e914 Migrate autoclose_fd_t to new file fds.h
fds.h will centralize logic around working with file descriptors. In
particular it will be the new home for logic around moving fds to high
unused values, replacing the "avoid conflicts" logic.
2021-02-05 17:58:08 -08:00

52 lines
1.2 KiB
C++

/** Facilities for working with file descriptors. */
#ifndef FISH_FDS_H
#define FISH_FDS_H
#include <algorithm>
/// A helper class for managing and automatically closing a file descriptor.
class autoclose_fd_t {
int fd_;
public:
// Closes the fd if not already closed.
void close();
// Returns the fd.
int fd() const { return fd_; }
// Returns the fd, transferring ownership to the caller.
int acquire() {
int temp = fd_;
fd_ = -1;
return temp;
}
// Resets to a new fd, taking ownership.
void reset(int fd) {
if (fd == fd_) return;
close();
fd_ = fd;
}
// \return if this has a valid fd.
bool valid() const { return fd_ >= 0; }
autoclose_fd_t(const autoclose_fd_t &) = delete;
void operator=(const autoclose_fd_t &) = delete;
autoclose_fd_t(autoclose_fd_t &&rhs) : fd_(rhs.fd_) { rhs.fd_ = -1; }
void operator=(autoclose_fd_t &&rhs) {
close();
std::swap(this->fd_, rhs.fd_);
}
explicit autoclose_fd_t(int fd = -1) : fd_(fd) {}
~autoclose_fd_t() { close(); }
};
/// Close a file descriptor \p fd, retrying on EINTR.
void exec_close(int fd);
#endif