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* */ |
bigbiff | 7b4c7a6 | 2015-01-01 19:44:14 -0500 | [diff] [blame] | 32 | usleep(250000); |
bigbiff bigbiff | e60683a | 2013-02-22 20:55:50 -0500 | [diff] [blame] | 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* */ |
Ethan Yonker | c798c9c | 2015-10-09 11:15:26 -0500 | [diff] [blame] | 52 | usleep(250000); |
bigbiff bigbiff | e60683a | 2013-02-22 20:55:50 -0500 | [diff] [blame] | 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) && |
bigbiff | 7b4c7a6 | 2015-01-01 19:44:14 -0500 | [diff] [blame] | 68 | (tries++ < 5)) { |
| 69 | usleep(250000); |
bigbiff bigbiff | e60683a | 2013-02-22 20:55:50 -0500 | [diff] [blame] | 70 | continue; |
bigbiff | 7b4c7a6 | 2015-01-01 19:44:14 -0500 | [diff] [blame] | 71 | } |
bigbiff bigbiff | e60683a | 2013-02-22 20:55:50 -0500 | [diff] [blame] | 72 | return c ? c : -1; |
| 73 | } |
| 74 | if (ret > 0) |
| 75 | tries = 0; |
| 76 | count -= ret; |
| 77 | buf += ret; |
| 78 | c += ret; |
| 79 | } |
| 80 | return c; |
| 81 | } |
| 82 | |
| 83 | |
| 84 | #endif /* UTIL_LINUX_ALL_IO_H */ |