Back to index

nagios-plugins  1.4.16
safe-read.c
Go to the documentation of this file.
00001 /* An interface to read and write that retries after interrupts.
00002 
00003    Copyright (C) 1993-1994, 1998, 2002-2006, 2009-2010 Free Software
00004    Foundation, Inc.
00005 
00006    This program is free software: you can redistribute it and/or modify
00007    it under the terms of the GNU General Public License as published by
00008    the Free Software Foundation; either version 3 of the License, or
00009    (at your option) any later version.
00010 
00011    This program is distributed in the hope that it will be useful,
00012    but WITHOUT ANY WARRANTY; without even the implied warranty of
00013    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00014    GNU General Public License for more details.
00015 
00016    You should have received a copy of the GNU General Public License
00017    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
00018 
00019 #include <config.h>
00020 
00021 /* Specification.  */
00022 #ifdef SAFE_WRITE
00023 # include "safe-write.h"
00024 #else
00025 # include "safe-read.h"
00026 #endif
00027 
00028 /* Get ssize_t.  */
00029 #include <sys/types.h>
00030 #include <unistd.h>
00031 
00032 #include <errno.h>
00033 
00034 #ifdef EINTR
00035 # define IS_EINTR(x) ((x) == EINTR)
00036 #else
00037 # define IS_EINTR(x) 0
00038 #endif
00039 
00040 #include <limits.h>
00041 
00042 #ifdef SAFE_WRITE
00043 # define safe_rw safe_write
00044 # define rw write
00045 #else
00046 # define safe_rw safe_read
00047 # define rw read
00048 # undef const
00049 # define const /* empty */
00050 #endif
00051 
00052 /* Read(write) up to COUNT bytes at BUF from(to) descriptor FD, retrying if
00053    interrupted.  Return the actual number of bytes read(written), zero for EOF,
00054    or SAFE_READ_ERROR(SAFE_WRITE_ERROR) upon error.  */
00055 size_t
00056 safe_rw (int fd, void const *buf, size_t count)
00057 {
00058   /* Work around a bug in Tru64 5.1.  Attempting to read more than
00059      INT_MAX bytes fails with errno == EINVAL.  See
00060      <http://lists.gnu.org/archive/html/bug-gnu-utils/2002-04/msg00010.html>.
00061      When decreasing COUNT, keep it block-aligned.  */
00062   enum { BUGGY_READ_MAXIMUM = INT_MAX & ~8191 };
00063 
00064   for (;;)
00065     {
00066       ssize_t result = rw (fd, buf, count);
00067 
00068       if (0 <= result)
00069         return result;
00070       else if (IS_EINTR (errno))
00071         continue;
00072       else if (errno == EINVAL && BUGGY_READ_MAXIMUM < count)
00073         count = BUGGY_READ_MAXIMUM;
00074       else
00075         return result;
00076     }
00077 }