1 /* Create a pipe, with specific opening flags.
2 Copyright (C) 2009, 2010 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, or (at your option)
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 along
15 with this program; if not, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
26 #include "binary-io.h"
28 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
29 /* Native Woe32 API. */
43 pipe2 (int fd[2], int flags)
47 /* Try the system call first, if it exists. (We may be running with a glibc
48 that has the function but with an older kernel that lacks it.) */
50 /* Cache the information whether the system call really exists. */
51 static int have_pipe2_really; /* 0 = unknown, 1 = yes, -1 = no */
52 if (have_pipe2_really >= 0)
54 int result = pipe2 (fd, flags);
55 if (!(result < 0 && errno == ENOSYS))
57 have_pipe2_really = 1;
60 have_pipe2_really = -1;
65 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
66 /* Native Woe32 API. */
68 /* Check the supported flags. */
69 if ((flags & ~(O_CLOEXEC | O_BINARY | O_TEXT)) != 0)
75 return _pipe (fd, 4096, flags);
80 /* Check the supported flags. */
81 if ((flags & ~(O_CLOEXEC | O_NONBLOCK | O_TEXT | O_BINARY)) != 0)
90 /* POSIX <http://www.opengroup.org/onlinepubs/9699919799/functions/pipe.html>
91 says that initially, the O_NONBLOCK and FD_CLOEXEC flags are cleared on
92 both fd[0] amd fd[1]. */
94 if (flags & O_NONBLOCK)
98 if ((fcntl_flags = fcntl (fd[1], F_GETFL, 0)) < 0
99 || fcntl (fd[1], F_SETFL, fcntl_flags | O_NONBLOCK) == -1
100 || (fcntl_flags = fcntl (fd[0], F_GETFL, 0)) < 0
101 || fcntl (fd[0], F_SETFL, fcntl_flags | O_NONBLOCK) == -1)
105 if (flags & O_CLOEXEC)
109 if ((fcntl_flags = fcntl (fd[1], F_GETFD, 0)) < 0
110 || fcntl (fd[1], F_SETFD, fcntl_flags | FD_CLOEXEC) == -1
111 || (fcntl_flags = fcntl (fd[0], F_GETFD, 0)) < 0
112 || fcntl (fd[0], F_SETFD, fcntl_flags | FD_CLOEXEC) == -1)
117 if (flags & O_BINARY)
119 setmode (fd[1], O_BINARY);
120 setmode (fd[0], O_BINARY);
122 else if (flags & O_TEXT)
124 setmode (fd[1], O_TEXT);
125 setmode (fd[0], O_TEXT);
133 int saved_errno = errno;