]> icculus.org git repositories - icculus/xz.git/blob - src/common/open_stdxxx.h
Imported to git.
[icculus/xz.git] / src / common / open_stdxxx.h
1 ///////////////////////////////////////////////////////////////////////////////
2 //
3 /// \file       open_stdxxx.h
4 /// \brief      Make sure that file descriptors 0, 1, and 2 are open
5 //
6 //  This code has been put into the public domain.
7 //
8 //  This library is distributed in the hope that it will be useful,
9 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
10 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11 //
12 ///////////////////////////////////////////////////////////////////////////////
13
14 #ifndef OPEN_STDXXX_H
15 #define OPEN_STDXXX_H
16
17 #include <stdlib.h>
18 #include <fcntl.h>
19 #include <unistd.h>
20
21
22 static void
23 open_stdxxx(int status)
24 {
25         for (int i = 0; i <= 2; ++i) {
26                 // We use fcntl() to check if the file descriptor is open.
27                 if (fcntl(i, F_GETFD) == -1 && errno == EBADF) {
28                         // With stdin, we could use /dev/full so that
29                         // writing to stdin would fail. However, /dev/full
30                         // is Linux specific, and if the program tries to
31                         // write to stdin, there's already a problem anyway.
32                         const int fd = open("/dev/null", O_NOCTTY
33                                         | (i == 0 ? O_WRONLY : O_RDONLY));
34
35                         if (fd != i) {
36                                 // Something went wrong. Exit with the
37                                 // exit status we were given. Don't try
38                                 // to print an error message, since stderr
39                                 // may very well be non-existent. This
40                                 // error should be extremely rare.
41                                 (void)close(fd);
42                                 exit(status);
43                         }
44                 }
45         }
46
47         return;
48 }
49
50 #endif