blob: 1fad66e533a353a4b80c9285aa1255a1a1dddd20 [file] [log] [blame]
bigbiff bigbiffe60683a2013-02-22 20:55:50 -05001/*
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
18static 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* */
bigbiff7b4c7a62015-01-01 19:44:14 -050032 usleep(250000);
bigbiff bigbiffe60683a2013-02-22 20:55:50 -050033 }
34 return 0;
35}
36
37static 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* */
bigbiff7b4c7a62015-01-01 19:44:14 -050052 xusleep(250000);
bigbiff bigbiffe60683a2013-02-22 20:55:50 -050053 }
54 return 0;
55}
56
57static 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) &&
bigbiff7b4c7a62015-01-01 19:44:14 -050068 (tries++ < 5)) {
69 usleep(250000);
bigbiff bigbiffe60683a2013-02-22 20:55:50 -050070 continue;
bigbiff7b4c7a62015-01-01 19:44:14 -050071 }
bigbiff bigbiffe60683a2013-02-22 20:55:50 -050072 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 */