]> git.cworth.org Git - tar/blob - gnu/fd-safer.c
upstream: Fix extraction of device nodes.
[tar] / gnu / fd-safer.c
1 /* -*- buffer-read-only: t -*- vi: set ro: */
2 /* DO NOT EDIT! GENERATED AUTOMATICALLY! */
3 /* Return a safer copy of a file descriptor.
4
5    Copyright (C) 2005-2006, 2009-2010 Free Software Foundation, Inc.
6
7    This program is free software: you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 /* Written by Paul Eggert.  */
21
22 #include <config.h>
23
24 #include "unistd-safer.h"
25
26 #include <errno.h>
27 #include <unistd.h>
28
29 /* Return FD, unless FD would be a copy of standard input, output, or
30    error; in that case, return a duplicate of FD, closing FD.  On
31    failure to duplicate, close FD, set errno, and return -1.  Preserve
32    errno if FD is negative, so that the caller can always inspect
33    errno when the returned value is negative.
34
35    This function is usefully wrapped around functions that return file
36    descriptors, e.g., fd_safer (open ("file", O_RDONLY)).  */
37
38 int
39 fd_safer (int fd)
40 {
41   if (STDIN_FILENO <= fd && fd <= STDERR_FILENO)
42     {
43       int f = dup_safer (fd);
44       int e = errno;
45       close (fd);
46       errno = e;
47       fd = f;
48     }
49
50   return fd;
51 }