mirror of
https://passt.top/passt
synced 2024-12-22 05:35:23 +00:00
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 <david@gibson.dropbear.id.au> Signed-off-by: Stefano Brivio <sbrivio@redhat.com>
This commit is contained in:
parent
bb41901c71
commit
bfc294b90d
3
pcap.c
3
pcap.c
@ -86,9 +86,8 @@ static void pcap_frame(const struct iovec *iov, size_t iovcnt,
|
||||
.caplen = l2len,
|
||||
.len = l2len
|
||||
};
|
||||
struct iovec hiov = { &h, sizeof(h) };
|
||||
|
||||
if (write_remainder(pcap_fd, &hiov, 1, 0) < 0 ||
|
||||
if (write_all_buf(pcap_fd, &h, sizeof(h)) < 0 ||
|
||||
write_remainder(pcap_fd, iov, iovcnt, offset) < 0)
|
||||
debug_perror("Cannot log packet, length %zu", l2len);
|
||||
}
|
||||
|
25
util.c
25
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
|
||||
|
1
util.h
1
util.h
@ -200,6 +200,7 @@ void pidfile_write(int fd, pid_t pid);
|
||||
int __daemon(int pidfile_fd, int devnull_fd);
|
||||
int fls(unsigned long x);
|
||||
int write_file(const char *path, const char *buf);
|
||||
int write_all_buf(int fd, const void *buf, size_t len);
|
||||
int write_remainder(int fd, const struct iovec *iov, size_t iovcnt, size_t skip);
|
||||
void close_open_files(int argc, char **argv);
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user