From 27b49a60d0fdb3b37ae6380896488b7e5381c6b9 Mon Sep 17 00:00:00 2001 From: sin-ack Date: Fri, 14 Jan 2022 13:22:54 +0000 Subject: [PATCH] LibCore: Implement LocalSocket::read_without_waiting This uses recv with MSG_DONTWAIT to disable blocking operation for a single call. LibIPC uses this to read in a non-blocking manner from an otherwise blocking socket. --- Userland/Libraries/LibCore/Stream.cpp | 11 ++++++++--- Userland/Libraries/LibCore/Stream.h | 3 ++- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/Userland/Libraries/LibCore/Stream.cpp b/Userland/Libraries/LibCore/Stream.cpp index 58d99e6349c..b24b56514f1 100644 --- a/Userland/Libraries/LibCore/Stream.cpp +++ b/Userland/Libraries/LibCore/Stream.cpp @@ -341,15 +341,15 @@ ErrorOr Socket::connect_inet(int fd, SocketAddress const& address) return {}; } -ErrorOr PosixSocketHelper::read(Bytes buffer) +ErrorOr PosixSocketHelper::read(Bytes buffer, int flags) { if (!is_open()) { return Error::from_errno(ENOTCONN); } - ssize_t rc = ::recv(m_fd, buffer.data(), buffer.size(), 0); + ssize_t rc = ::recv(m_fd, buffer.data(), buffer.size(), flags); if (rc < 0) { - return Error::from_errno(errno); + return Error::from_syscall("recv", -errno); } m_last_read_was_eof = rc == 0; @@ -556,4 +556,9 @@ ErrorOr LocalSocket::send_fd(int fd) #endif } +ErrorOr LocalSocket::read_without_waiting(Bytes buffer) +{ + return m_helper.read(buffer, MSG_DONTWAIT); +} + } diff --git a/Userland/Libraries/LibCore/Stream.h b/Userland/Libraries/LibCore/Stream.h index 7999eef53c4..d3820ab3797 100644 --- a/Userland/Libraries/LibCore/Stream.h +++ b/Userland/Libraries/LibCore/Stream.h @@ -229,7 +229,7 @@ public: int fd() const { return m_fd; } void set_fd(int fd) { m_fd = fd; } - ErrorOr read(Bytes); + ErrorOr read(Bytes, int flags = 0); ErrorOr write(ReadonlyBytes); bool is_eof() const { return !is_open() || m_last_read_was_eof; } @@ -412,6 +412,7 @@ public: ErrorOr receive_fd(int flags); ErrorOr send_fd(int fd); + ErrorOr read_without_waiting(Bytes buffer); virtual ~LocalSocket() { close(); }