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 2, 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. */
36 pipe2 (int fd[2], int flags)
40 /* Try the system call first, if it exists. (We may be running with a glibc
41 that has the function but with an older kernel that lacks it.) */
43 /* Cache the information whether the system call really exists. */
44 static int have_pipe2_really; /* 0 = unknown, 1 = yes, -1 = no */
45 if (have_pipe2_really >= 0)
47 int result = pipe2 (fd, flags);
48 if (!(result < 0 && errno == ENOSYS))
50 have_pipe2_really = 1;
53 have_pipe2_really = -1;
58 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
59 /* Native Woe32 API. */
61 /* Check the supported flags. */
62 if ((flags & ~(O_CLOEXEC | O_BINARY | O_TEXT)) != 0)
68 return _pipe (fd, 4096, flags);
73 /* Check the supported flags. */
74 if ((flags & ~(O_CLOEXEC | O_NONBLOCK | O_TEXT | O_BINARY)) != 0)
83 /* POSIX <http://www.opengroup.org/onlinepubs/9699919799/functions/pipe.html>
84 says that initially, the O_NONBLOCK and FD_CLOEXEC flags are cleared on
85 both fd[0] amd fd[1]. */
87 if (flags & O_NONBLOCK)
91 if ((fcntl_flags = fcntl (fd[1], F_GETFL, 0)) < 0
92 || fcntl (fd[1], F_SETFL, fcntl_flags | O_NONBLOCK) == -1
93 || (fcntl_flags = fcntl (fd[0], F_GETFL, 0)) < 0
94 || fcntl (fd[0], F_SETFL, fcntl_flags | O_NONBLOCK) == -1)
98 if (flags & O_CLOEXEC)
102 if ((fcntl_flags = fcntl (fd[1], F_GETFD, 0)) < 0
103 || fcntl (fd[1], F_SETFD, fcntl_flags | FD_CLOEXEC) == -1
104 || (fcntl_flags = fcntl (fd[0], F_GETFD, 0)) < 0
105 || fcntl (fd[0], F_SETFD, fcntl_flags | FD_CLOEXEC) == -1)
110 if (flags & O_BINARY)
112 setmode (fd[1], O_BINARY);
113 setmode (fd[0], O_BINARY);
115 else if (flags & O_TEXT)
117 setmode (fd[1], O_TEXT);
118 setmode (fd[0], O_TEXT);
126 int saved_errno = errno;