Port: Add Solaris support to socket compat
[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 #define _GNU_SOURCE
19 #define _LGPL_SOURCE
20 #include <assert.h>
21 #include <errno.h>
22 #include <limits.h>
23 #include <unistd.h>
24
25 #include "readwrite.h"
26
27 /*
28 * lttng_read and lttng_write take care of EINTR and partial read/write.
29 * Upon success, they return the "count" received as parameter.
30 * They can return a negative value if an error occurs.
31 * If a value lower than the requested "count" is returned, it means an
32 * error occured.
33 * The error can be checked by querying errno.
34 */
35 LTTNG_HIDDEN
36 ssize_t lttng_read(int fd, void *buf, size_t count)
37 {
38 size_t i = 0;
39 ssize_t ret;
40
41 assert(buf);
42
43 /*
44 * Deny a read count that can be bigger then the returned value max size.
45 * This makes the function to never return an overflow value.
46 */
47 if (count > SSIZE_MAX) {
48 return -EINVAL;
49 }
50
51 do {
52 ret = read(fd, buf + i, count - i);
53 if (ret < 0) {
54 if (errno == EINTR) {
55 continue; /* retry operation */
56 } else {
57 goto error;
58 }
59 }
60 i += ret;
61 assert(i <= count);
62 } while (count - i > 0 && ret > 0);
63 return i;
64
65 error:
66 if (i == 0) {
67 return -1;
68 } else {
69 return i;
70 }
71 }
72
73 LTTNG_HIDDEN
74 ssize_t lttng_write(int fd, const void *buf, size_t count)
75 {
76 size_t i = 0;
77 ssize_t ret;
78
79 assert(buf);
80
81 /*
82 * Deny a write count that can be bigger then the returned value max size.
83 * This makes the function to never return an overflow value.
84 */
85 if (count > SSIZE_MAX) {
86 return -EINVAL;
87 }
88
89 do {
90 ret = write(fd, buf + i, count - i);
91 if (ret < 0) {
92 if (errno == EINTR) {
93 continue; /* retry operation */
94 } else {
95 goto error;
96 }
97 }
98 i += ret;
99 assert(i <= count);
100 } while (count - i > 0 && ret > 0);
101 return i;
102
103 error:
104 if (i == 0) {
105 return -1;
106 } else {
107 return i;
108 }
109 }
This page took 0.031136 seconds and 4 git commands to generate.