186d7f5d3SJohn Marino /* Invoke dup, but avoid some glitches.
286d7f5d3SJohn Marino Copyright (C) 2001, 2004, 2005 Free Software Foundation, Inc.
386d7f5d3SJohn Marino
486d7f5d3SJohn Marino This program is free software; you can redistribute it and/or modify
586d7f5d3SJohn Marino it under the terms of the GNU General Public License as published by
686d7f5d3SJohn Marino the Free Software Foundation; either version 2, or (at your option)
786d7f5d3SJohn Marino any later version.
886d7f5d3SJohn Marino
986d7f5d3SJohn Marino This program is distributed in the hope that it will be useful,
1086d7f5d3SJohn Marino but WITHOUT ANY WARRANTY; without even the implied warranty of
1186d7f5d3SJohn Marino MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1286d7f5d3SJohn Marino GNU General Public License for more details.
1386d7f5d3SJohn Marino
1486d7f5d3SJohn Marino You should have received a copy of the GNU General Public License
1586d7f5d3SJohn Marino along with this program; if not, write to the Free Software Foundation,
1686d7f5d3SJohn Marino Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
1786d7f5d3SJohn Marino
1886d7f5d3SJohn Marino /* Written by Paul Eggert. */
1986d7f5d3SJohn Marino
2086d7f5d3SJohn Marino #ifdef HAVE_CONFIG_H
2186d7f5d3SJohn Marino # include <config.h>
2286d7f5d3SJohn Marino #endif
2386d7f5d3SJohn Marino
2486d7f5d3SJohn Marino #include "unistd-safer.h"
2586d7f5d3SJohn Marino
2686d7f5d3SJohn Marino #include <fcntl.h>
2786d7f5d3SJohn Marino
2886d7f5d3SJohn Marino #include <unistd.h>
2986d7f5d3SJohn Marino #ifndef STDERR_FILENO
3086d7f5d3SJohn Marino # define STDERR_FILENO 2
3186d7f5d3SJohn Marino #endif
3286d7f5d3SJohn Marino
3386d7f5d3SJohn Marino /* Like dup, but do not return STDIN_FILENO, STDOUT_FILENO, or
3486d7f5d3SJohn Marino STDERR_FILENO. */
3586d7f5d3SJohn Marino
3686d7f5d3SJohn Marino int
dup_safer(int fd)3786d7f5d3SJohn Marino dup_safer (int fd)
3886d7f5d3SJohn Marino {
3986d7f5d3SJohn Marino #ifdef F_DUPFD
4086d7f5d3SJohn Marino return fcntl (fd, F_DUPFD, STDERR_FILENO + 1);
4186d7f5d3SJohn Marino #else
4286d7f5d3SJohn Marino /* fd_safer calls us back, but eventually the recursion unwinds and
4386d7f5d3SJohn Marino does the right thing. */
4486d7f5d3SJohn Marino return fd_safer (dup (fd));
4586d7f5d3SJohn Marino #endif
4686d7f5d3SJohn Marino }
47