42424535831794dcdc3c7fd29a97e79a89dfadd9
[gnulib.git] / lib / isatty.c
1 /* isatty() replacement.
2    Copyright (C) 2012 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
16
17 #include <config.h>
18
19 /* Specification.  */
20 #include <unistd.h>
21
22 /* This replacement is enabled on native Windows.  */
23
24 #include <errno.h>
25
26 /* Get declarations of the Win32 API functions.  */
27 #define WIN32_LEAN_AND_MEAN
28 #include <windows.h>
29
30 #include "msvc-inval.h"
31
32 /* Get _get_osfhandle().  */
33 #include "msvc-nothrow.h"
34
35 /* Optimized test whether a HANDLE refers to a console.
36    See <http://lists.gnu.org/archive/html/bug-gnulib/2009-08/msg00065.html>.  */
37 #define IsConsoleHandle(h) (((intptr_t) (h) & 3) == 3)
38
39 #if HAVE_MSVC_INVALID_PARAMETER_HANDLER
40 static inline int
41 _isatty_nothrow (int fd)
42 {
43   int result;
44
45   TRY_MSVC_INVAL
46     {
47       result = _isatty (fd);
48     }
49   CATCH_MSVC_INVAL
50     {
51       result = -1;
52       errno = EBADF;
53     }
54   DONE_MSVC_INVAL;
55
56   return result;
57 }
58 #else
59 # define _isatty_nothrow _isatty
60 #endif
61
62 int
63 isatty (int fd)
64 {
65   /* _isatty (fd) tests whether GetFileType of the handle is FILE_TYPE_CHAR.  */
66   if (_isatty_nothrow (fd))
67     {
68       HANDLE h = (HANDLE) _get_osfhandle (fd);
69       return IsConsoleHandle (h);
70     }
71   else
72     return 0;
73 }