Clean-up: remove instances of loop initial declarations
[lttng-tools.git] / src / common / readwrite.c
... / ...
CommitLineData
1/*
2 * Copyright (C) 2013 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
3 *
4 * SPDX-License-Identifier: LGPL-2.1-only
5 *
6 */
7
8#define _LGPL_SOURCE
9#include <assert.h>
10#include <errno.h>
11#include <limits.h>
12#include <unistd.h>
13
14#include "readwrite.h"
15
16/*
17 * lttng_read and lttng_write take care of EINTR and partial read/write.
18 * Upon success, they return the "count" received as parameter.
19 * They can return a negative value if an error occurs.
20 * If a value lower than the requested "count" is returned, it means an
21 * error occurred.
22 * The error can be checked by querying errno.
23 */
24LTTNG_HIDDEN
25ssize_t lttng_read(int fd, void *buf, size_t count)
26{
27 size_t i = 0;
28 ssize_t ret;
29
30 assert(buf);
31
32 /*
33 * Deny a read count that can be bigger then the returned value max size.
34 * This makes the function to never return an overflow value.
35 */
36 if (count > SSIZE_MAX) {
37 return -EINVAL;
38 }
39
40 do {
41 ret = read(fd, buf + i, count - i);
42 if (ret < 0) {
43 if (errno == EINTR) {
44 continue; /* retry operation */
45 } else {
46 goto error;
47 }
48 }
49 i += ret;
50 assert(i <= count);
51 } while (count - i > 0 && ret > 0);
52 return i;
53
54error:
55 if (i == 0) {
56 return -1;
57 } else {
58 return i;
59 }
60}
61
62LTTNG_HIDDEN
63ssize_t lttng_write(int fd, const void *buf, size_t count)
64{
65 size_t i = 0;
66 ssize_t ret;
67
68 assert(buf);
69
70 /*
71 * Deny a write count that can be bigger then the returned value max size.
72 * This makes the function to never return an overflow value.
73 */
74 if (count > SSIZE_MAX) {
75 return -EINVAL;
76 }
77
78 do {
79 ret = write(fd, buf + i, count - i);
80 if (ret < 0) {
81 if (errno == EINTR) {
82 continue; /* retry operation */
83 } else {
84 goto error;
85 }
86 }
87 i += ret;
88 assert(i <= count);
89 } while (count - i > 0 && ret > 0);
90 return i;
91
92error:
93 if (i == 0) {
94 return -1;
95 } else {
96 return i;
97 }
98}
This page took 0.024514 seconds and 4 git commands to generate.