]> icculus.org git repositories - icculus/xz.git/blob - src/common/tuklib_open_stdxxx.c
Fix incorrect use of "restrict".
[icculus/xz.git] / src / common / tuklib_open_stdxxx.c
1 ///////////////////////////////////////////////////////////////////////////////
2 //
3 /// \file       tuklib_open_stdxxx.c
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 #include "tuklib_open_stdxxx.h"
14
15 #ifndef TUKLIB_DOSLIKE
16 #       include <stdlib.h>
17 #       include <errno.h>
18 #       include <fcntl.h>
19 #       include <unistd.h>
20 #endif
21
22
23 extern void
24 tuklib_open_stdxxx(int err_status)
25 {
26 #ifndef TUKLIB_DOSLIKE
27         for (int i = 0; i <= 2; ++i) {
28                 // We use fcntl() to check if the file descriptor is open.
29                 if (fcntl(i, F_GETFD) == -1 && errno == EBADF) {
30                         // With stdin, we could use /dev/full so that
31                         // writing to stdin would fail. However, /dev/full
32                         // is Linux specific, and if the program tries to
33                         // write to stdin, there's already a problem anyway.
34                         const int fd = open("/dev/null", O_NOCTTY
35                                         | (i == 0 ? O_WRONLY : O_RDONLY));
36
37                         if (fd != i) {
38                                 // Something went wrong. Exit with the
39                                 // exit status we were given. Don't try
40                                 // to print an error message, since stderr
41                                 // may very well be non-existent. This
42                                 // error should be extremely rare.
43                                 (void)close(fd);
44                                 exit(err_status);
45                         }
46                 }
47         }
48 #endif
49
50         return;
51 }