]> mj.ucw.cz Git - libucw.git/blob - ucw/io-careful.c
io-careful: Do not fail if a system call is interrupted by a signal
[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 <unistd.h>
15
16 /*
17  *  Reads and writes on sockets and pipes can return partial results,
18  *  so we implement an iterated read/write call.
19  */
20
21 int
22 careful_read(int fd, void *buf, size_t len)
23 {
24   byte *pos = buf;
25   while (len)
26     {
27       ssize_t l = read(fd, pos, len);
28       if (l < 0)
29         {
30           if (errno == EINTR)
31             continue;
32           return -1;
33         }
34       if (!l)
35         return 0;
36       pos += l;
37       len -= l;
38     }
39   return 1;
40 }
41
42 int
43 careful_write(int fd, const void *buf, size_t len)
44 {
45   const byte *pos = buf;
46   while (len)
47     {
48       ssize_t l = write(fd, pos, len);
49       if (l < 0)
50         {
51           if (errno == EINTR)
52             continue;
53           return -1;
54         }
55       if (!l)
56         return 0;
57       pos += l;
58       len -= l;
59     }
60   return 1;
61 }