recognize new archive, audio, image formats; give audio files a separate color
[platform/upstream/coreutils.git] / lib / stdopen.c
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 2, 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, write to the Free Software Foundation,
17    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
18
19 /* Written by Paul Eggert and Jim Meyering.  */
20
21 #include <config.h>
22
23 #include "stdopen.h"
24
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <fcntl.h>
28 #include <unistd.h>
29 #include <errno.h>
30
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.  */
37 bool
38 stdopen (void)
39 {
40   int fd;
41   bool ok = true;
42
43   for (fd = 0; fd <= 2; fd++)
44     {
45       if (fcntl (fd, F_GETFD) < 0)
46         {
47           if (errno != EBADF)
48             ok = false;
49           else
50             {
51               static const int contrary_mode[]
52                 = { O_WRONLY, O_RDONLY, O_RDONLY };
53               int mode = contrary_mode[fd];
54               int new_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.  */
61               if (mode == O_RDONLY
62                   || (new_fd = open ("/dev/full", mode) != fd))
63                 new_fd = open ("/dev/null", mode);
64               if (new_fd != fd)
65                 {
66                   if (0 <= new_fd)
67                     close (new_fd);
68                   ok = false;
69                 }
70             }
71         }
72     }
73
74   return ok;
75 }