195a9066b9e0c00b8a59053a20bbbffeb295ad0d
[gnulib.git] / tests / test-isatty.c
1 /* Test isatty() function.
2    Copyright (C) 2011-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 #include <unistd.h>
20
21 #include "signature.h"
22 SIGNATURE_CHECK (isatty, int, (int));
23
24 #include <errno.h>
25 #include <fcntl.h>
26
27 #include "macros.h"
28
29 /* The name of the "always silent" device.  */
30 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
31 /* Native Windows API.  */
32 # define DEV_NULL "NUL"
33 #else
34 /* Unix API.  */
35 # define DEV_NULL "/dev/null"
36 #endif
37
38 int
39 main (void)
40 {
41   const char *file = "test-isatty.txt";
42
43   /* Test behaviour for invalid file descriptors.  */
44   {
45     errno = 0;
46     ASSERT (isatty (-1) == 0);
47     ASSERT (errno == EBADF
48             || errno == 0 /* seen on IRIX 6.5, Solaris 10 */
49            );
50   }
51   {
52     errno = 0;
53     ASSERT (isatty (99) == 0);
54     ASSERT (errno == EBADF
55             || errno == 0 /* seen on IRIX 6.5, Solaris 10 */
56            );
57   }
58
59   /* Test behaviour for regular files.  */
60   {
61     int fd;
62
63     fd = open (file, O_WRONLY|O_CREAT|O_TRUNC, 0644);
64     ASSERT (0 <= fd);
65     ASSERT (write (fd, "hello", 5) == 5);
66     ASSERT (close (fd) == 0);
67
68     fd = open (file, O_RDONLY);
69     ASSERT (0 <= fd);
70     ASSERT (! isatty (fd));
71     ASSERT (close (fd) == 0);
72   }
73
74   /* Test behaviour for pipes.  */
75   {
76     int fd[2];
77
78     ASSERT (pipe (fd) == 0);
79     ASSERT (! isatty (fd[0]));
80     ASSERT (! isatty (fd[1]));
81     ASSERT (close (fd[0]) == 0);
82     ASSERT (close (fd[1]) == 0);
83   }
84
85   /* Test behaviour for /dev/null.  */
86   {
87     int fd;
88
89     fd = open (DEV_NULL, O_RDONLY);
90     ASSERT (0 <= fd);
91     ASSERT (! isatty (fd));
92     ASSERT (close (fd) == 0);
93   }
94
95   ASSERT (unlink (file) == 0);
96
97   return 0;
98 }