#ifndef STRAWBERRY_PROC_READ_HPP #define STRAWBERRY_PROC_READ_HPP // Non-throwing, bounded reads of small text files (/proc, /sys, config). // // Never read /proc with iostreams: when the process exits mid-read the read // fails with ESRCH and libstdc++ throws std::ios_base::failure from the stream // buffer (std::istreambuf_iterator does not catch it). On 2026-10-25 that // uncaught exception aborted the daemon, and the core dump then deadlocked // with the exec guard and froze the host. #include #include #include #include #include "strawberry/sys_io.hpp" namespace strawberry { /// Whole file up to `max_bytes` (truncated beyond). nullopt if it cannot be /// opened or a read fails (e.g. the process exited: ESRCH). inline std::optional read_small_file(const std::string& path, std::size_t max_bytes = 1u << 20) { const int fd = io::open(path.c_str(), O_RDONLY | O_CLOEXEC | O_NOCTTY); if (fd < 0) { return std::nullopt; } std::string out; char buffer[8192]; int interrupted = 0; while (out.size() < max_bytes) { const ssize_t n = io::read(fd, buffer, sizeof(buffer)); if (n < 0) { if (errno == EINTR && ++interrupted < io::kMaxEintrRetries) { continue; } io::close(fd); return std::nullopt; } if (n == 0) { break; } out.append(buffer, static_cast(n) < max_bytes - out.size() ? static_cast(n) : max_bytes - out.size()); } io::close(fd); return out; } /// Same, empty string on any failure. inline std::string read_small_file_or_empty(const std::string& path, std::size_t max_bytes = 1u << 20) { return read_small_file(path, max_bytes).value_or(std::string{}); } } // namespace strawberry #endif // STRAWBERRY_PROC_READ_HPP