Back to index

nagios-plugins  1.4.16
fd-safer.c
Go to the documentation of this file.
00001 /* Return a safer copy of a file descriptor.
00002 
00003    Copyright (C) 2005-2006, 2009-2010 Free Software Foundation, Inc.
00004 
00005    This program is free software: you can redistribute it and/or modify
00006    it under the terms of the GNU General Public License as published by
00007    the Free Software Foundation; either version 3 of the License, or
00008    (at your option) any later version.
00009 
00010    This program is distributed in the hope that it will be useful,
00011    but WITHOUT ANY WARRANTY; without even the implied warranty of
00012    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00013    GNU General Public License for more details.
00014 
00015    You should have received a copy of the GNU General Public License
00016    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
00017 
00018 /* Written by Paul Eggert.  */
00019 
00020 #include <config.h>
00021 
00022 #include "unistd-safer.h"
00023 
00024 #include <errno.h>
00025 #include <unistd.h>
00026 
00027 /* Return FD, unless FD would be a copy of standard input, output, or
00028    error; in that case, return a duplicate of FD, closing FD.  On
00029    failure to duplicate, close FD, set errno, and return -1.  Preserve
00030    errno if FD is negative, so that the caller can always inspect
00031    errno when the returned value is negative.
00032 
00033    This function is usefully wrapped around functions that return file
00034    descriptors, e.g., fd_safer (open ("file", O_RDONLY)).  */
00035 
00036 int
00037 fd_safer (int fd)
00038 {
00039   if (STDIN_FILENO <= fd && fd <= STDERR_FILENO)
00040     {
00041       int f = dup_safer (fd);
00042       int e = errno;
00043       close (fd);
00044       errno = e;
00045       fd = f;
00046     }
00047 
00048   return fd;
00049 }