Zth (libzth)
Loading...
Searching...
No Matches
io.cpp
Go to the documentation of this file.
1/*
2 * SPDX-FileCopyrightText: 2019-2026 Jochem Rutgers
3 *
4 * SPDX-License-Identifier: MPL-2.0
5 */
6
7#include <libzth/config.h>
8#include <libzth/io.h>
9#include <libzth/poller.h>
10#include <libzth/util.h>
11#include <libzth/worker.h>
12#include <libzth/zmq.h>
13
14#if defined(ZTH_HAVE_POLLER) && !defined(ZTH_OS_WINDOWS)
15# include <fcntl.h>
16
17namespace zth {
18namespace io {
19
24ssize_t read(int fd, void* buf, size_t count)
25{
26 perf_syscall("read()");
27
28 int flags = fcntl(fd, F_GETFL);
29 if(unlikely(flags == -1))
30 return -1; // with errno set
31
32 // NOLINTNEXTLINE(hicpp-signed-bitwise)
33 if((flags & O_NONBLOCK)) {
34 zth_dbg(io, "[%s] read(%d) non-blocking", currentFiber().str().c_str(), fd);
35 // Just do the call.
36 return ::read(fd, buf, count);
37 }
38
39 errno = zth::poll(PollableFd(fd, Pollable::PollIn), -1);
40 if(errno)
41 return -1;
42
43 // Got data to read.
44 zth_dbg(io, "[%s] read(%d)", currentFiber().str().c_str(), fd);
45 return ::read(fd, buf, count);
46}
47
52ssize_t write(int fd, void const* buf, size_t count)
53{
54 perf_syscall("write()");
55
56 int flags = fcntl(fd, F_GETFL);
57 if(unlikely(flags == -1))
58 return -1; // with errno set
59
60 // NOLINTNEXTLINE(hicpp-signed-bitwise)
61 if((flags & O_NONBLOCK)) {
62 zth_dbg(io, "[%s] write(%d) non-blocking", currentFiber().str().c_str(), fd);
63 // Just do the call.
64 return ::write(fd, buf, count);
65 }
66
67 errno = zth::poll(PollableFd(fd, Pollable::PollOut), -1);
68 if(errno)
69 return -1;
70
71 // Go write the data.
72 zth_dbg(io, "[%s] write(%d)", currentFiber().str().c_str(), fd);
73 return ::write(fd, buf, count);
74}
75
76} // namespace io
77} // namespace zth
78#else
79static int no_io __attribute__((unused));
80#endif // ZTH_HAVE_POLLER
Fiber & currentFiber() noexcept
Return the currently executing fiber.
Definition worker.h:417
ssize_t read(int fd, void *buf, size_t count)
Like normal read(), but forwards the poll() to the zth::Waiter in case it would block.
Definition io.cpp:24
ssize_t write(int fd, void const *buf, size_t count)
Like normal write(), but forwards the poll() to the zth::Waiter in case it would block.
Definition io.cpp:52
int poll(P pollable, int timeout_ms=-1)
Fiber-aware poll() for a single pollable thing.
Definition poller.h:784
#define zth_dbg(group, fmt, a...)
Debug printf()-like function.
Definition util.h:194
cow_string str(T value)
Returns an zth::string representation of the given value.
Definition util.h:497
void perf_syscall(char const *syscall, Timestamp const &t=Timestamp())
Put a syscall into the perf output.
Definition perf.h:361
A pollable file descriptor.
Definition poller.h:135
static const unsigned long PollIn
Definition poller.h:89
static const unsigned long PollOut
Definition poller.h:90
#define unlikely(expr)
Marks the given expression to likely be evaluated to true.
Definition util.h:60