]> icculus.org git repositories - icculus/xz.git/blob - src/common/open_stdxxx.h
Put the interesting parts of XZ Utils into the public domain.
[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 //  Author:     Lasse Collin
7 //
8 //  This file has been put into the public domain.
9 //  You can do whatever you want with this file.
10 //
11 ///////////////////////////////////////////////////////////////////////////////
12
13 #ifndef OPEN_STDXXX_H
14 #define OPEN_STDXXX_H
15
16 #include <stdlib.h>
17 #include <fcntl.h>
18 #include <unistd.h>
19
20
21 static void
22 open_stdxxx(int status)
23 {
24         for (int i = 0; i <= 2; ++i) {
25                 // We use fcntl() to check if the file descriptor is open.
26                 if (fcntl(i, F_GETFD) == -1 && errno == EBADF) {
27                         // With stdin, we could use /dev/full so that
28                         // writing to stdin would fail. However, /dev/full
29                         // is Linux specific, and if the program tries to
30                         // write to stdin, there's already a problem anyway.
31                         const int fd = open("/dev/null", O_NOCTTY
32                                         | (i == 0 ? O_WRONLY : O_RDONLY));
33
34                         if (fd != i) {
35                                 // Something went wrong. Exit with the
36                                 // exit status we were given. Don't try
37                                 // to print an error message, since stderr
38                                 // may very well be non-existent. This
39                                 // error should be extremely rare.
40                                 (void)close(fd);
41                                 exit(status);
42                         }
43                 }
44         }
45
46         return;
47 }
48
49 #endif