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 (flags & O_NONBLOCK)
71 int result = _pipe (fd, 4096, flags & ~O_NONBLOCK);
74 if (set_nonblocking_flag (fd[0], true) != 0
75 || set_nonblocking_flag (fd[1], true) != 0)
77 int saved_errno = errno;
85 return _pipe (fd, 4096, flags);
93 /* POSIX <http://www.opengroup.org/onlinepubs/9699919799/functions/pipe.html>
94 says that initially, the O_NONBLOCK and FD_CLOEXEC flags are cleared on
95 both fd[0] and fd[1]. */
97 if (flags & O_NONBLOCK)
101 if ((fcntl_flags = fcntl (fd[1], F_GETFL, 0)) < 0
102 || fcntl (fd[1], F_SETFL, fcntl_flags | O_NONBLOCK) == -1
103 || (fcntl_flags = fcntl (fd[0], F_GETFL, 0)) < 0
104 || fcntl (fd[0], F_SETFL, fcntl_flags | O_NONBLOCK) == -1)
108 if (flags & O_CLOEXEC)
112 if ((fcntl_flags = fcntl (fd[1], F_GETFD, 0)) < 0
113 || fcntl (fd[1], F_SETFD, fcntl_flags | FD_CLOEXEC) == -1
114 || (fcntl_flags = fcntl (fd[0], F_GETFD, 0)) < 0
115 || fcntl (fd[0], F_SETFD, fcntl_flags | FD_CLOEXEC) == -1)
120 if (flags & O_BINARY)
122 setmode (fd[1], O_BINARY);
123 setmode (fd[0], O_BINARY);
125 else if (flags & O_TEXT)
127 setmode (fd[1], O_TEXT);
128 setmode (fd[0], O_TEXT);
136 int saved_errno = errno;