Make it possible to use the list in signal-handlers.
[gnulib.git] / lib / safe-read.c
1 /* An interface to read and write that retries after interrupts.
2
3    Copyright (C) 1993, 1994, 1998, 2002, 2003, 2004, 2005 Free Software
4    Foundation, Inc.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2, or (at your option)
9    any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software Foundation,
18    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
19
20 #ifdef HAVE_CONFIG_H
21 # include <config.h>
22 #endif
23
24 /* Specification.  */
25 #ifdef SAFE_WRITE
26 # include "safe-write.h"
27 #else
28 # include "safe-read.h"
29 #endif
30
31 /* Get ssize_t.  */
32 #include <sys/types.h>
33 #include <unistd.h>
34
35 #include <errno.h>
36
37 #ifdef EINTR
38 # define IS_EINTR(x) ((x) == EINTR)
39 #else
40 # define IS_EINTR(x) 0
41 #endif
42
43 #include <limits.h>
44
45 #ifdef SAFE_WRITE
46 # define safe_rw safe_write
47 # define rw write
48 #else
49 # define safe_rw safe_read
50 # define rw read
51 # undef const
52 # define const /* empty */
53 #endif
54
55 /* Read(write) up to COUNT bytes at BUF from(to) descriptor FD, retrying if
56    interrupted.  Return the actual number of bytes read(written), zero for EOF,
57    or SAFE_READ_ERROR(SAFE_WRITE_ERROR) upon error.  */
58 size_t
59 safe_rw (int fd, void const *buf, size_t count)
60 {
61   /* Work around a bug in Tru64 5.1.  Attempting to read more than
62      INT_MAX bytes fails with errno == EINVAL.  See
63      <http://lists.gnu.org/archive/html/bug-gnu-utils/2002-04/msg00010.html>.
64      When decreasing COUNT, keep it block-aligned.  */
65   enum { BUGGY_READ_MAXIMUM = INT_MAX & ~8191 };
66
67   for (;;)
68     {
69       ssize_t result = rw (fd, buf, count);
70
71       if (0 <= result)
72         return result;
73       else if (IS_EINTR (errno))
74         continue;
75       else if (errno == EINVAL && BUGGY_READ_MAXIMUM < count)
76         count = BUGGY_READ_MAXIMUM;
77       else
78         return result;
79     }
80 }