From bfc294b90dc46d132a56dc0a2ae118f2bea5a266 Mon Sep 17 00:00:00 2001 From: David Gibson Date: Wed, 18 Sep 2024 20:44:05 +1000 Subject: util: Add helper to write() all of a buffer write(2) might not write all the data it is given. Add a write_all_buf() helper to keep calling it until all the given data is written, or we get an error. Currently we use write_remainder() to do this operation in pcap_frame(). That's a little awkward since it requires constructing an iovec, and future changes we want to make to write_remainder() will be easier in terms of this single buffer helper. Signed-off-by: David Gibson Signed-off-by: Stefano Brivio --- util.c | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) (limited to 'util.c') diff --git a/util.c b/util.c index eede4e5..7db7c2e 100644 --- a/util.c +++ b/util.c @@ -582,6 +582,31 @@ int do_clone(int (*fn)(void *), char *stack_area, size_t stack_size, int flags, #endif } +/* write_all_buf() - write all of a buffer to an fd + * @fd: File descriptor + * @buf: Pointer to base of buffer + * @len: Length of buffer + * + * Return: 0 on success, -1 on error (with errno set) + * + * #syscalls write + */ +int write_all_buf(int fd, const void *buf, size_t len) +{ + const char *p = buf; + size_t left = len; + + while (left) { + ssize_t rc = write(fd, p, left); + + if (rc < 0) + return -1; + p += rc; + left -= rc; + } + return 0; +} + /* write_remainder() - write the tail of an IO vector to an fd * @fd: File descriptor * @iov: IO vector -- cgit v1.2.3