| 1 |
/* stdopen.c - ensure that the three standard file descriptors are in use |
| 2 |
|
| 3 |
Copyright (C) 2005-2006, 2019-2025 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 <https://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/stat.h> |
| 25 |
#include <fcntl.h> |
| 26 |
#include <unistd.h> |
| 27 |
#include <errno.h> |
| 28 |
|
| 29 |
/* Try to ensure that all of the standard file numbers (0, 1, 2) |
| 30 |
are in use. Without this, each application would have to guard |
| 31 |
every call to open, dup, fopen, etc. with tests to ensure they |
| 32 |
don't use one of the special file numbers when opening a file. |
| 33 |
Return zero if successful, an errno value if at least one of |
| 34 |
the file descriptors is initially closed and could not be opened. */ |
| 35 |
|
| 36 |
int |
| 37 |
stdopen (void) |
| 38 |
{ |
| 39 |
int fd; |
| 40 |
for (fd = STDIN_FILENO; fd <= STDERR_FILENO; fd++) |
| 41 |
{ |
| 42 |
if (fcntl (fd, F_GETFD) < 0) |
| 43 |
{ |
| 44 |
/* Open /dev/null with the contrary mode so that the typical |
| 45 |
read (stdin) or write (stdout, stderr) operation will fail. |
| 46 |
With descriptor 0, we can do even better on systems that |
| 47 |
have /dev/full, by opening that write-only instead of |
| 48 |
/dev/null. The only drawback is that a write-provoked |
| 49 |
failure comes with a misleading errno value, ENOSPC. */ |
| 50 |
int mode = fd == STDIN_FILENO ? O_WRONLY : O_RDONLY; |
| 51 |
int full_fd = fd == STDIN_FILENO ? open ("/dev/full", mode) : -1; |
| 52 |
int new_fd = full_fd < 0 ? open ("/dev/null", mode) : full_fd; |
| 53 |
if (new_fd < 0) |
| 54 |
return errno; |
| 55 |
if (STDERR_FILENO < new_fd) |
| 56 |
{ |
| 57 |
/* 0, 1, and 2 are already open somehow. |
| 58 |
Our is not to reason why. */ |
| 59 |
close (new_fd); |
| 60 |
return 0; |
| 61 |
} |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
return 0; |
| 66 |
} |