Fix: add asserts and remove unused variable
[lttng-tools.git] / src / common / readwrite.c
1 /*
2 * Copyright (C) 2013 - Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
3 *
4 * This library is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU Lesser General Public License, version 2.1 only,
6 * as published by the Free Software Foundation.
7 *
8 * This library is distributed in the hope that it will be useful, but WITHOUT
9 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
11 * for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public License
14 * along with this library; if not, write to the Free Software Foundation,
15 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16 */
17
18 #include <assert.h>
19 #include <errno.h>
20 #include <unistd.h>
21
22 #include "readwrite.h"
23
24 /*
25 * lttng_read and lttng_write take care of EINTR and partial read/write.
26 * Upon success, they return the "count" received as parameter.
27 * They can return a negative value if an error occurs.
28 * If a value lower than the requested "count" is returned, it means an
29 * error occured.
30 * The error can be checked by querying errno.
31 */
32 ssize_t lttng_read(int fd, void *buf, size_t count)
33 {
34 size_t i = 0;
35 ssize_t ret;
36
37 assert(fd >= 0);
38 assert(buf);
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
54 error:
55 if (i == 0) {
56 return -1;
57 } else {
58 return i;
59 }
60 }
61
62 ssize_t lttng_write(int fd, const void *buf, size_t count)
63 {
64 size_t i = 0;
65 ssize_t ret;
66
67 assert(fd >= 0);
68 assert(buf);
69
70 do {
71 ret = write(fd, buf + i, count - i);
72 if (ret < 0) {
73 if (errno == EINTR) {
74 continue; /* retry operation */
75 } else {
76 goto error;
77 }
78 }
79 i += ret;
80 assert(i <= count);
81 } while (count - i > 0 && ret > 0);
82 return i;
83
84 error:
85 if (i == 0) {
86 return -1;
87 } else {
88 return i;
89 }
90 }
This page took 0.030197 seconds and 4 git commands to generate.