]> mj.ucw.cz Git - libucw.git/blob - ucw/io-careful.c
io-careful: Fixed missing #include
[libucw.git] / ucw / io-careful.c
1 /*
2  *      UCW Library -- Careful Read/Write
3  *
4  *      (c) 2004--2012 Martin Mares <mj@ucw.cz>
5  *      (c) 2020 Jan Filip Chadima <jfch@jagda.eu>
6  *
7  *      This software may be freely distributed and used according to the terms
8  *      of the GNU Lesser General Public License.
9  */
10
11 #include <ucw/lib.h>
12 #include <ucw/io.h>
13
14 #include <errno.h>
15 #include <unistd.h>
16
17 /*
18  *  Reads and writes on sockets and pipes can return partial results,
19  *  so we implement an iterated read/write call.
20  */
21
22 int
23 careful_read(int fd, void *buf, size_t len)
24 {
25   byte *pos = buf;
26   while (len)
27     {
28       ssize_t l = read(fd, pos, len);
29       if (l < 0)
30         {
31           if (errno == EINTR)
32             continue;
33           return -1;
34         }
35       if (!l)
36         return 0;
37       pos += l;
38       len -= l;
39     }
40   return 1;
41 }
42
43 int
44 careful_write(int fd, const void *buf, size_t len)
45 {
46   const byte *pos = buf;
47   while (len)
48     {
49       ssize_t l = write(fd, pos, len);
50       if (l < 0)
51         {
52           if (errno == EINTR)
53             continue;
54           return -1;
55         }
56       if (!l)
57         return 0;
58       pos += l;
59       len -= l;
60     }
61   return 1;
62 }