1 /* stdopen.c - ensure that the three standard file descriptors are in use
3 Copyright (C) 2005, 2006 Free Software Foundation, Inc.
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 2, or (at your option)
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.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software Foundation,
17 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
19 /* Written by Paul Eggert and Jim Meyering. */
25 #include <sys/types.h>
31 /* Try to ensure that all of the standard file numbers (0, 1, 2)
32 are in use. Without this, each application would have to guard
33 every call to open, dup, fopen, etc. with tests to ensure they
34 don't use one of the special file numbers when opening a file.
35 Return false if at least one of the file descriptors is initially
36 closed and an attempt to reopen it fails. Otherwise, return true. */
43 for (fd
= 0; fd
<= 2; fd
++)
45 if (fcntl (fd
, F_GETFD
) < 0)
51 static const int contrary_mode
[]
52 = { O_WRONLY
, O_RDONLY
, O_RDONLY
};
53 int mode
= contrary_mode
[fd
];
55 /* Open /dev/null with the contrary mode so that the typical
56 read (stdin) or write (stdout, stderr) operation will fail.
57 With descriptor 0, we can do even better on systems that
58 have /dev/full, by opening that write-only instead of
59 /dev/null. The only drawback is that a write-provoked
60 failure comes with a misleading errno value, ENOSPC. */
62 || (new_fd
= open ("/dev/full", mode
) != fd
))
63 new_fd
= open ("/dev/null", mode
);