fchdir: avoid extra chdir and fix test
[gnulib.git] / m4 / dup2.m4
1 #serial 12
2 dnl Copyright (C) 2002, 2005, 2007, 2009-2011 Free Software Foundation, Inc.
3 dnl This file is free software; the Free Software Foundation
4 dnl gives unlimited permission to copy and/or distribute it,
5 dnl with or without modifications, as long as this notice is preserved.
6
7 AC_DEFUN([gl_FUNC_DUP2],
8 [
9   AC_REQUIRE([gl_UNISTD_H_DEFAULTS])
10   AC_REQUIRE([AC_CANONICAL_HOST])
11   m4_ifdef([gl_FUNC_DUP2_OBSOLETE], [
12     AC_CHECK_FUNCS_ONCE([dup2])
13     if test $ac_cv_func_dup2 = no; then
14       HAVE_DUP2=0
15       AC_LIBOBJ([dup2])
16     fi
17   ], [
18     AC_DEFINE([HAVE_DUP2], [1], [Define to 1 if you have the 'dup2' function.])
19   ])
20   AC_CHECK_FUNCS_ONCE([fcntl])
21   if test $HAVE_DUP2 = 1; then
22     AC_CACHE_CHECK([whether dup2 works], [gl_cv_func_dup2_works],
23       [AC_RUN_IFELSE([
24          AC_LANG_PROGRAM([[#include <unistd.h>
25 #include <fcntl.h>
26 #include <errno.h>]],
27            [int result = 0;
28 #if HAVE_FCNTL
29             if (fcntl (1, F_SETFD, FD_CLOEXEC) == -1)
30               result |= 1;
31 #endif HAVE_FCNTL
32             if (dup2 (1, 1) == 0)
33               result |= 2;
34 #if HAVE_FCNTL
35             if (fcntl (1, F_GETFD) != FD_CLOEXEC)
36               result |= 4;
37 #endif
38             close (0);
39             if (dup2 (0, 0) != -1)
40               result |= 8;
41             /* Many gnulib modules require POSIX conformance of EBADF.  */
42             if (dup2 (2, 1000000) == -1 && errno != EBADF)
43               result |= 16;
44             return result;
45            ])
46         ],
47         [gl_cv_func_dup2_works=yes], [gl_cv_func_dup2_works=no],
48         [case "$host_os" in
49            mingw*) # on this platform, dup2 always returns 0 for success
50              gl_cv_func_dup2_works=no;;
51            cygwin*) # on cygwin 1.5.x, dup2(1,1) returns 0
52              gl_cv_func_dup2_works=no;;
53            linux*) # On linux between 2008-07-27 and 2009-05-11, dup2 of a
54                    # closed fd may yield -EBADF instead of -1 / errno=EBADF.
55              gl_cv_func_dup2_works=no;;
56            freebsd*) # on FreeBSD 6.1, dup2(1,1000000) gives EMFILE, not EBADF.
57              gl_cv_func_dup2_works=no;;
58            haiku*) # on Haiku alpha 2, dup2(1, 1) resets FD_CLOEXEC.
59              gl_cv_func_dup2_works=no;;
60            *) gl_cv_func_dup2_works=yes;;
61          esac])
62       ])
63     if test "$gl_cv_func_dup2_works" = no; then
64       gl_REPLACE_DUP2
65     fi
66   fi
67 ])
68
69 AC_DEFUN([gl_REPLACE_DUP2],
70 [
71   AC_REQUIRE([gl_UNISTD_H_DEFAULTS])
72   AC_CHECK_FUNCS_ONCE([dup2])
73   if test $ac_cv_func_dup2 = yes; then
74     REPLACE_DUP2=1
75   fi
76   AC_LIBOBJ([dup2])
77 ])