mirror of
https://github.com/fish-shell/fish-shell
synced 2025-01-22 09:45:47 +00:00
53 lines
1.2 KiB
C
53 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
|