1 /* SPDX-License-Identifier: LGPL-2.1+ */
11 #include "time-util.h"
13 int flush_fd(int fd) {
14 struct pollfd pollfd = {
20 /* Read from the specified file descriptor, until POLLIN is not set anymore, throwing away everything
21 * read. Note that some file descriptors (notable IP sockets) will trigger POLLIN even when no data can be read
22 * (due to IP packet checksum mismatches), hence this function is only safe to be non-blocking if the fd used
23 * was set to non-blocking too. */
30 r = poll(&pollfd, 1, 0);
40 l = read(fd, buf, sizeof(buf));
57 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
64 /* If called with nbytes == 0, let's call read() at least
65 * once, to validate the operation */
67 if (nbytes > (size_t) SSIZE_MAX)
73 k = read(fd, p, nbytes);
78 if (errno == EAGAIN && do_poll) {
80 /* We knowingly ignore any return value here,
81 * and expect that any error/EOF is reported
84 (void) fd_wait_for_event(fd, POLLIN, USEC_INFINITY);
88 return n > 0 ? n : -errno;
94 assert((size_t) k <= nbytes);
104 int loop_read_exact(int fd, void *buf, size_t nbytes, bool do_poll) {
107 n = loop_read(fd, buf, nbytes, do_poll);
110 if ((size_t) n != nbytes)
116 int loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
117 const uint8_t *p = buf;
122 if (_unlikely_(nbytes > (size_t) SSIZE_MAX))
128 k = write(fd, p, nbytes);
133 if (errno == EAGAIN && do_poll) {
134 /* We knowingly ignore any return value here,
135 * and expect that any error/EOF is reported
138 (void) fd_wait_for_event(fd, POLLOUT, USEC_INFINITY);
145 if (_unlikely_(nbytes > 0 && k == 0)) /* Can't really happen */
148 assert((size_t) k <= nbytes);
152 } while (nbytes > 0);
157 int pipe_eof(int fd) {
158 struct pollfd pollfd = {
160 .events = POLLIN|POLLHUP,
165 r = poll(&pollfd, 1, 0);
172 return pollfd.revents & POLLHUP;
175 int fd_wait_for_event(int fd, int event, usec_t t) {
177 struct pollfd pollfd = {
185 r = ppoll(&pollfd, 1, t == USEC_INFINITY ? NULL : timespec_store(&ts, t), NULL);
191 return pollfd.revents;
194 static size_t nul_length(const uint8_t *p, size_t sz) {
209 ssize_t sparse_write(int fd, const void *p, size_t sz, size_t run_length) {
210 const uint8_t *q, *w, *e;
218 n = nul_length(q, e - q);
220 /* If there are more than the specified run length of
221 * NUL bytes, or if this is the beginning or the end
222 * of the buffer, then seek instead of write */
223 if ((n > run_length) ||
225 (n > 0 && q + n >= e)) {
227 l = write(fd, w, q - w);
234 if (lseek(fd, n, SEEK_CUR) == (off_t) -1)
246 l = write(fd, w, q - w);
253 return q - (const uint8_t*) p;