1 |
/* stdopen.c - ensure that the three standard file descriptors are in use |
2 |
|
3 |
Copyright (C) 2005, 2006 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 of the License, or |
8 |
(at your option) 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 |
#include <config.h> |
21 |
|
22 |
#include "stdopen.h" |
23 |
|
24 |
#include <sys/types.h> |
25 |
#include <sys/stat.h> |
26 |
#include <fcntl.h> |
27 |
#include <unistd.h> |
28 |
#include <errno.h> |
29 |
|
30 |
/* Try to ensure that all of the standard file numbers (0, 1, 2) |
31 |
are in use. Without this, each application would have to guard |
32 |
every call to open, dup, fopen, etc. with tests to ensure they |
33 |
don't use one of the special file numbers when opening a file. |
34 |
Return false if at least one of the file descriptors is initially |
35 |
closed and an attempt to reopen it fails. Otherwise, return true. */ |
36 |
bool |
37 |
stdopen (void) |
38 |
{ |
39 |
int fd; |
40 |
bool ok = true; |
41 |
|
42 |
for (fd = 0; fd <= 2; fd++) |
43 |
{ |
44 |
if (fcntl (fd, F_GETFD) < 0) |
45 |
{ |
46 |
if (errno != EBADF) |
47 |
ok = false; |
48 |
else |
49 |
{ |
50 |
static const int contrary_mode[] |
51 |
= { O_WRONLY, O_RDONLY, O_RDONLY }; |
52 |
int mode = contrary_mode[fd]; |
53 |
int new_fd; |
54 |
/* Open /dev/null with the contrary mode so that the typical |
55 |
read (stdin) or write (stdout, stderr) operation will fail. |
56 |
With descriptor 0, we can do even better on systems that |
57 |
have /dev/full, by opening that write-only instead of |
58 |
/dev/null. The only drawback is that a write-provoked |
59 |
failure comes with a misleading errno value, ENOSPC. */ |
60 |
if (mode == O_RDONLY |
61 |
|| (new_fd = open ("/dev/full", mode) != fd)) |
62 |
new_fd = open ("/dev/null", mode); |
63 |
if (new_fd != fd) |
64 |
{ |
65 |
if (0 <= new_fd) |
66 |
close (new_fd); |
67 |
ok = false; |
68 |
} |
69 |
} |
70 |
} |
71 |
} |
72 |
|
73 |
return ok; |
74 |
} |