1 /* Test duplicating file descriptors.
2 Copyright (C) 2009 Free Software Foundation, Inc.
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.
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.
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/>. */
17 /* Written by Eric Blake <ebb9@byu.net>, 2009. */
28 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
29 /* Get declarations of the Win32 API functions. */
30 # define WIN32_LEAN_AND_MEAN
34 #define ASSERT(expr) \
39 fprintf (stderr, "%s:%d: assertion failed\n", __FILE__, __LINE__); \
46 /* Return non-zero if FD is open. */
50 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
51 /* On Win32, the initial state of unassigned standard file
52 descriptors is that they are open but point to an
53 INVALID_HANDLE_VALUE, and there is no fcntl. */
54 return (HANDLE) _get_osfhandle (fd) != INVALID_HANDLE_VALUE;
57 # error Please port fcntl to your platform
59 return 0 <= fcntl (fd, F_GETFL);
66 const char *file = "test-dup2.tmp";
68 int fd = open (file, O_CREAT | O_RDWR, 0600);
70 /* Assume std descriptors were provided by invoker. */
71 ASSERT (STDERR_FILENO < fd);
72 ASSERT (is_open (fd));
73 /* Ignore any other fd's leaked into this process. */
76 ASSERT (!is_open (fd + 1));
77 ASSERT (!is_open (fd + 2));
79 /* Assigning to self must be a no-op. */
80 ASSERT (dup2 (fd, fd) == fd);
81 ASSERT (is_open (fd));
83 /* If the source is not open, then the destination is unaffected. */
85 ASSERT (dup2 (fd + 1, fd + 1) == -1);
86 ASSERT (errno == EBADF);
87 ASSERT (!is_open (fd + 1));
89 ASSERT (dup2 (fd + 1, fd) == -1);
90 ASSERT (errno == EBADF);
91 ASSERT (is_open (fd));
93 /* The destination must be valid. */
95 ASSERT (dup2 (fd, -2) == -1);
96 ASSERT (errno == EBADF);
98 /* Using dup2 can skip fds. */
99 ASSERT (dup2 (fd, fd + 2) == fd + 2);
100 ASSERT (is_open (fd));
101 ASSERT (!is_open (fd + 1));
102 ASSERT (is_open (fd + 2));
104 /* Prove that dup2 closes the previous occupant of a fd. */
105 ASSERT (open ("/dev/null", O_WRONLY, 0600) == fd + 1);
106 ASSERT (dup2 (fd + 1, fd) == fd);
107 ASSERT (close (fd + 1) == 0);
108 ASSERT (write (fd, "1", 1) == 1);
109 ASSERT (dup2 (fd + 2, fd) == fd);
110 ASSERT (write (fd + 2, "2", 1) == 1);
111 ASSERT (lseek (fd, SEEK_SET, 0) == 0);
112 ASSERT (read (fd, buffer, 1) == 1);
113 ASSERT (*buffer == '2');
116 ASSERT (close (fd + 2) == 0);
117 ASSERT (close (fd) == 0);
118 ASSERT (unlink (file) == 0);