| 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(buf); |
| 38 | |
| 39 | do { |
| 40 | ret = read(fd, buf + i, count - i); |
| 41 | if (ret < 0) { |
| 42 | if (errno == EINTR) { |
| 43 | continue; /* retry operation */ |
| 44 | } else { |
| 45 | goto error; |
| 46 | } |
| 47 | } |
| 48 | i += ret; |
| 49 | assert(i <= count); |
| 50 | } while (count - i > 0 && ret > 0); |
| 51 | return i; |
| 52 | |
| 53 | error: |
| 54 | if (i == 0) { |
| 55 | return -1; |
| 56 | } else { |
| 57 | return i; |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | ssize_t lttng_write(int fd, const void *buf, size_t count) |
| 62 | { |
| 63 | size_t i = 0; |
| 64 | ssize_t ret; |
| 65 | |
| 66 | assert(buf); |
| 67 | |
| 68 | do { |
| 69 | ret = write(fd, buf + i, count - i); |
| 70 | if (ret < 0) { |
| 71 | if (errno == EINTR) { |
| 72 | continue; /* retry operation */ |
| 73 | } else { |
| 74 | goto error; |
| 75 | } |
| 76 | } |
| 77 | i += ret; |
| 78 | assert(i <= count); |
| 79 | } while (count - i > 0 && ret > 0); |
| 80 | return i; |
| 81 | |
| 82 | error: |
| 83 | if (i == 0) { |
| 84 | return -1; |
| 85 | } else { |
| 86 | return i; |
| 87 | } |
| 88 | } |