1 /* Test of reopening a stream.
2 Copyright (C) 2009-2018 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 <https://www.gnu.org/licenses/>. */
16
17 /* Written by Eric Blake <ebb9@byu.net>, 2009. */
18
19 #include <config.h>
20
21 /* Specification. */
22 #include "stdio--.h"
23
24 /* Helpers. */
25 #include <unistd.h>
26
27 /* This test intentionally closes stderr. So, we arrange to have fd 10
28 (outside the range of interesting fd's during the test) set up to
29 duplicate the original stderr. */
30
31 #define BACKUP_STDERR_FILENO 10
32 #define ASSERT_STREAM myerr
33 #include "macros.h"
34
35 static FILE *myerr;
36
37 int
main(void)38 main (void)
39 {
40 FILE *fp;
41
42 /* We close fd 2 later, so save it in fd 10. */
43 if (dup2 (STDERR_FILENO, BACKUP_STDERR_FILENO) != BACKUP_STDERR_FILENO
44 || (myerr = fdopen (BACKUP_STDERR_FILENO, "w")) == NULL)
45 return 2;
46
47 {
48 FILE *tmp;
49 ASSERT (tmp = fopen ("/dev/null", "r"));
50 ASSERT (STDERR_FILENO < fileno (tmp));
51 ASSERT (fp = fopen ("/dev/null", "w"));
52 ASSERT (fileno (tmp) < fileno (fp));
53 ASSERT (fclose (tmp) == 0);
54 }
55
56 /* Gap in fds. */
57 ASSERT (freopen ("/dev/null", "r+", fp) == fp);
58 ASSERT (STDERR_FILENO < fileno (fp));
59
60 ASSERT (freopen ("/dev/null", "r", stdin) == stdin);
61 ASSERT (STDIN_FILENO == fileno (stdin));
62
63 ASSERT (freopen ("/dev/null", "w", stdout) == stdout);
64 ASSERT (STDOUT_FILENO == fileno (stdout));
65
66 ASSERT (freopen ("/dev/null", "w", stderr) == stderr);
67 ASSERT (STDERR_FILENO == fileno (stderr));
68
69 /* fd 0 closed. */
70 ASSERT (close (STDIN_FILENO) == 0);
71
72 ASSERT (freopen ("/dev/null", "w", stdout) == stdout);
73 ASSERT (STDOUT_FILENO == fileno (stdout));
74
75 ASSERT (freopen ("/dev/null", "w", stderr) == stderr);
76 ASSERT (STDERR_FILENO == fileno (stderr));
77
78 ASSERT (freopen ("/dev/null", "a", fp) == fp);
79 ASSERT (STDERR_FILENO < fileno (fp));
80
81 /* fd 1 closed. */
82 ASSERT (close (STDOUT_FILENO) == 0);
83
84 ASSERT (freopen ("/dev/null", "w", stderr) == stderr);
85 ASSERT (STDERR_FILENO == fileno (stderr));
86
87 ASSERT (freopen ("/dev/null", "a+", fp) == fp);
88 ASSERT (STDERR_FILENO < fileno (fp));
89
90 /* fd 2 closed. */
91 ASSERT (close (STDERR_FILENO) == 0);
92
93 ASSERT (freopen ("/dev/null", "w+", fp) == fp);
94 ASSERT (STDERR_FILENO < fileno (fp));
95
96 return 0;
97 }
98