diff options
author | Tom Hubrecht <github@mail.hubrecht.ovh> | 2024-05-28 12:25:49 +0200 |
---|---|---|
committer | Tom Hubrecht <github@mail.hubrecht.ovh> | 2024-05-29 09:54:47 +0200 |
commit | 8cd9aa24a8d48caf22225ce32dff3c5aaa111687 (patch) | |
tree | 27ea642636e1e47d37053f5fd4d209e29f4a9149 /src/libutil/file-descriptor.hh | |
parent | 6b5078c81554ddb36547f8c41805cc94b7738396 (diff) |
util.{hh,cc}: Split out file-descriptor.{hh,cc}
Change-Id: I0dd0f9a9c2003fb887e076127e7f825fd3289c76
Diffstat (limited to 'src/libutil/file-descriptor.hh')
-rw-r--r-- | src/libutil/file-descriptor.hh | 89 |
1 files changed, 89 insertions, 0 deletions
diff --git a/src/libutil/file-descriptor.hh b/src/libutil/file-descriptor.hh new file mode 100644 index 000000000..68324b9d9 --- /dev/null +++ b/src/libutil/file-descriptor.hh @@ -0,0 +1,89 @@ +#pragma once +///@file + +#include "error.hh" + +namespace nix { + +struct Sink; +struct Source; + +/** + * Read a line from a file descriptor. + */ +std::string readLine(int fd); + +/** + * Write a line to a file descriptor. + */ +void writeLine(int fd, std::string s); + +/** + * Read the contents of a file into a string. + */ +std::string readFile(int fd); + +/** + * Wrappers arount read()/write() that read/write exactly the + * requested number of bytes. + */ +void readFull(int fd, char * buf, size_t count); +void writeFull(int fd, std::string_view s, bool allowInterrupts = true); + +/** + * Read a file descriptor until EOF occurs. + */ +std::string drainFD(int fd, bool block = true, const size_t reserveSize=0); + +void drainFD(int fd, Sink & sink, bool block = true); + +class AutoCloseFD +{ + int fd; +public: + AutoCloseFD(); + explicit AutoCloseFD(int fd); + AutoCloseFD(const AutoCloseFD & fd) = delete; + AutoCloseFD(AutoCloseFD&& fd); + ~AutoCloseFD(); + AutoCloseFD& operator =(const AutoCloseFD & fd) = delete; + AutoCloseFD& operator =(AutoCloseFD&& fd) noexcept(false); + int get() const; + explicit operator bool() const; + int release(); + void close(); + void fsync(); + void reset() { *this = {}; } +}; + +class Pipe +{ +public: + AutoCloseFD readSide, writeSide; + void create(); + void close(); +}; + +/** + * Close all file descriptors except those listed in the given set. + * Good practice in child processes. + */ +void closeMostFDs(const std::set<int> & exceptions); + +/** + * Set the close-on-exec flag for the given file descriptor. + */ +void closeOnExec(int fd); + +MakeError(EndOfFile, Error); + +/** + * Create a Unix domain socket. + */ +AutoCloseFD createUnixDomainSocket(); + +/** + * Create a Unix domain socket in listen mode. + */ +AutoCloseFD createUnixDomainSocket(const Path & path, mode_t mode); +} |