re-mark 1.29b-2 as not yet uploaded (merge madness!)
[debian/tar] / lib / stdopen.c
1 /* stdopen.c - ensure that the three standard file descriptors are in use
2
3    Copyright 2005, 2007, 2013-2014, 2016 Free Software Foundation, Inc.
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 3, or (at your option)
8    any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
17
18 /* Written by Paul Eggert and Jim Meyering.  */
19
20 #ifdef HAVE_CONFIG_H
21 # include <config.h>
22 #endif
23
24 #include "stdopen.h"
25
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <fcntl.h>
29 #include <unistd.h>
30 #include <errno.h>
31
32 /* Try to ensure that all of the standard file numbers (0, 1, 2)
33    are in use.  Without this, each application would have to guard
34    every call to open, dup, fopen, etc. with tests to ensure they
35    don't use one of the special file numbers when opening a file.
36    Return false if at least one of the file descriptors is initially
37    closed and an attempt to reopen it fails.  Otherwise, return true.  */
38 bool
39 stdopen (void)
40 {
41   int fd;
42   bool ok = true;
43
44   for (fd = 0; fd <= 2; fd++)
45     {
46       if (fcntl (fd, F_GETFD) < 0)
47         {
48           if (errno != EBADF)
49             ok = false;
50           else
51             {
52               static const int contrary_mode[]
53                 = { O_WRONLY, O_RDONLY, O_RDONLY };
54               int mode = contrary_mode[fd];
55               int new_fd;
56               /* Open /dev/null with the contrary mode so that the typical
57                  read (stdin) or write (stdout, stderr) operation will fail.
58                  With descriptor 0, we can do even better on systems that
59                  have /dev/full, by opening that write-only instead of
60                  /dev/null.  The only drawback is that a write-provoked
61                  failure comes with a misleading errno value, ENOSPC.  */
62               if (mode == O_RDONLY
63                   || (new_fd = open ("/dev/full", mode) != fd))
64                 new_fd = open ("/dev/null", mode);
65               if (new_fd != fd)
66                 {
67                   if (0 <= new_fd)
68                     close (new_fd);
69                   ok = false;
70                 }
71             }
72         }
73     }
74
75   return ok;
76 }