bigbiff bigbiff | e60683a | 2013-02-22 20:55:50 -0500 | [diff] [blame] | 1 | /* |
| 2 | * No copyright is claimed. This code is in the public domain; do with |
| 3 | * it what you wish. |
| 4 | * |
| 5 | * Written by Karel Zak <kzak@redhat.com> |
| 6 | * Petr Uzel <petr.uzel@suse.cz> |
| 7 | */ |
| 8 | |
| 9 | #ifndef UTIL_LINUX_ALL_IO_H |
| 10 | #define UTIL_LINUX_ALL_IO_H |
| 11 | |
| 12 | #include <string.h> |
| 13 | #include <unistd.h> |
| 14 | #include <errno.h> |
| 15 | |
| 16 | #include "c.h" |
| 17 | |
| 18 | static inline int write_all(int fd, const void *buf, size_t count) |
| 19 | { |
| 20 | while (count) { |
| 21 | ssize_t tmp; |
| 22 | |
| 23 | errno = 0; |
| 24 | tmp = write(fd, buf, count); |
| 25 | if (tmp > 0) { |
| 26 | count -= tmp; |
| 27 | if (count) |
| 28 | buf = (void *) ((char *) buf + tmp); |
| 29 | } else if (errno != EINTR && errno != EAGAIN) |
| 30 | return -1; |
| 31 | if (errno == EAGAIN) /* Try later, *sigh* */ |
| 32 | usleep(10000); |
| 33 | } |
| 34 | return 0; |
| 35 | } |
| 36 | |
| 37 | static inline int fwrite_all(const void *ptr, size_t size, |
| 38 | size_t nmemb, FILE *stream) |
| 39 | { |
| 40 | while (nmemb) { |
| 41 | size_t tmp; |
| 42 | |
| 43 | errno = 0; |
| 44 | tmp = fwrite(ptr, size, nmemb, stream); |
| 45 | if (tmp > 0) { |
| 46 | nmemb -= tmp; |
| 47 | if (nmemb) |
| 48 | ptr = (void *) ((char *) ptr + (tmp * size)); |
| 49 | } else if (errno != EINTR && errno != EAGAIN) |
| 50 | return -1; |
| 51 | if (errno == EAGAIN) /* Try later, *sigh* */ |
| 52 | usleep(10000); |
| 53 | } |
| 54 | return 0; |
| 55 | } |
| 56 | |
| 57 | static inline ssize_t read_all(int fd, char *buf, size_t count) |
| 58 | { |
| 59 | ssize_t ret; |
| 60 | ssize_t c = 0; |
| 61 | int tries = 0; |
| 62 | |
| 63 | memset(buf, 0, count); |
| 64 | while (count > 0) { |
| 65 | ret = read(fd, buf, count); |
| 66 | if (ret <= 0) { |
| 67 | if ((errno == EAGAIN || errno == EINTR || ret == 0) && |
| 68 | (tries++ < 5)) |
| 69 | continue; |
| 70 | return c ? c : -1; |
| 71 | } |
| 72 | if (ret > 0) |
| 73 | tries = 0; |
| 74 | count -= ret; |
| 75 | buf += ret; |
| 76 | c += ret; |
| 77 | } |
| 78 | return c; |
| 79 | } |
| 80 | |
| 81 | |
| 82 | #endif /* UTIL_LINUX_ALL_IO_H */ |