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);
71 ASSERT (is_open (fd));
72 ASSERT (!is_open (fd + 1));
73 ASSERT (!is_open (fd + 2));
75 /* Assigning to self must be a no-op. */
76 ASSERT (dup2 (fd, fd) == fd);
77 ASSERT (is_open (fd));
79 /* If the source is not open, then the destination is unaffected. */
81 ASSERT (dup2 (fd + 1, fd + 1) == -1);
82 ASSERT (errno == EBADF);
83 ASSERT (!is_open (fd + 1));
85 ASSERT (dup2 (fd + 1, fd) == -1);
86 ASSERT (errno == EBADF);
87 ASSERT (is_open (fd));
89 /* The destination must be valid. */
91 ASSERT (dup2 (fd, -2) == -1);
92 ASSERT (errno == EBADF);
94 /* Using dup2 can skip fds. */
95 ASSERT (dup2 (fd, fd + 2) == fd + 2);
96 ASSERT (is_open (fd));
97 ASSERT (!is_open (fd + 1));
98 ASSERT (is_open (fd + 2));
100 /* Prove that dup2 closes the previous occupant of a fd. */
101 ASSERT (open ("/dev/null", O_WRONLY, 0600) == fd + 1);
102 ASSERT (dup2 (fd + 1, fd) == fd);
103 ASSERT (close (fd + 1) == 0);
104 ASSERT (write (fd, "1", 1) == 1);
105 ASSERT (dup2 (fd + 2, fd) == fd);
106 ASSERT (write (fd + 2, "2", 1) == 1);
107 ASSERT (lseek (fd, SEEK_SET, 0) == 0);
108 ASSERT (read (fd, buffer, 1) == 1);
109 ASSERT (*buffer == '2');
112 ASSERT (close (fd + 2) == 0);
113 ASSERT (close (fd) == 0);
114 ASSERT (unlink (file) == 0);