1 /* Create a pipe, with specific opening flags.
2 Copyright (C) 2009-2011 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"
27 #include "nonblocking.h"
29 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
30 /* Native Woe32 API. */
37 pipe2 (int fd[2], int flags)
41 /* Try the system call first, if it exists. (We may be running with a glibc
42 that has the function but with an older kernel that lacks it.) */
44 /* Cache the information whether the system call really exists. */
45 static int have_pipe2_really; /* 0 = unknown, 1 = yes, -1 = no */
46 if (have_pipe2_really >= 0)
48 int result = pipe2 (fd, flags);
49 if (!(result < 0 && errno == ENOSYS))
51 have_pipe2_really = 1;
54 have_pipe2_really = -1;
59 /* Check the supported flags. */
60 if ((flags & ~(O_CLOEXEC | O_NONBLOCK | O_BINARY | O_TEXT)) != 0)
66 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
67 /* Native Woe32 API. */
69 if (_pipe (fd, 4096, flags & ~O_NONBLOCK) < 0)
72 if (flags & O_NONBLOCK)
74 if (set_nonblocking_flag (fd[0], true) != 0
75 || set_nonblocking_flag (fd[1], true) != 0)
87 /* POSIX <http://www.opengroup.org/onlinepubs/9699919799/functions/pipe.html>
88 says that initially, the O_NONBLOCK and FD_CLOEXEC flags are cleared on
89 both fd[0] and fd[1]. */
91 if (flags & O_NONBLOCK)
95 if ((fcntl_flags = fcntl (fd[1], F_GETFL, 0)) < 0
96 || fcntl (fd[1], F_SETFL, fcntl_flags | O_NONBLOCK) == -1
97 || (fcntl_flags = fcntl (fd[0], F_GETFL, 0)) < 0
98 || fcntl (fd[0], F_SETFL, fcntl_flags | O_NONBLOCK) == -1)
102 if (flags & O_CLOEXEC)
106 if ((fcntl_flags = fcntl (fd[1], F_GETFD, 0)) < 0
107 || fcntl (fd[1], F_SETFD, fcntl_flags | FD_CLOEXEC) == -1
108 || (fcntl_flags = fcntl (fd[0], F_GETFD, 0)) < 0
109 || fcntl (fd[0], F_SETFD, fcntl_flags | FD_CLOEXEC) == -1)
114 if (flags & O_BINARY)
116 setmode (fd[1], O_BINARY);
117 setmode (fd[0], O_BINARY);
119 else if (flags & O_TEXT)
121 setmode (fd[1], O_TEXT);
122 setmode (fd[0], O_TEXT);
132 int saved_errno = errno;