/[coreutils]/coreutils/lib/stdopen.c
ViewVC logotype

Contents of /coreutils/lib/stdopen.c

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.11 - (show annotations) (download)
Mon Jul 23 18:41:11 2007 UTC (16 years, 10 months ago) by meyering
Branch: MAIN
CVS Tags: DU-FTS, v6_9, textutils-1_12_1, CPPI-1_12, CPPI-1_11, CPPI-1_10, ISDIGIT-bug-fix, CPPI-1_9, CPPI-1_8, HEAD
Changes since 1.10: +4 -5 lines
File MIME type: text/plain
Update all copyright notices to use the newer form.


Author: Jim Meyering <jim@meyering.net>

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 }

savannah-hackers-public@gnu.org
ViewVC Help
Powered by ViewVC 1.1.26