1 /*
2 * poll_posix: poll compatibility wrapper for POSIX systems
3 * Copyright © 2013 RealVNC Ltd.
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18 *
19 */
20
21 #include <config.h>
22
23 #include <unistd.h>
24 #include <fcntl.h>
25 #include <errno.h>
26 #include <stdlib.h>
27
28 #include "libusbi.h"
29
usbi_pipe(int pipefd[2])30 int usbi_pipe(int pipefd[2])
31 {
32 #if defined(HAVE_PIPE2)
33 int ret = pipe2(pipefd, O_CLOEXEC);
34 #else
35 int ret = pipe(pipefd);
36 #endif
37
38 if (ret != 0) {
39 usbi_err(NULL, "failed to create pipe (%d)", errno);
40 return ret;
41 }
42
43 #if !defined(HAVE_PIPE2) && defined(FD_CLOEXEC)
44 ret = fcntl(pipefd[0], F_GETFD);
45 if (ret == -1) {
46 usbi_err(NULL, "failed to get pipe fd flags (%d)", errno);
47 goto err_close_pipe;
48 }
49 ret = fcntl(pipefd[0], F_SETFD, ret | FD_CLOEXEC);
50 if (ret == -1) {
51 usbi_err(NULL, "failed to set pipe fd flags (%d)", errno);
52 goto err_close_pipe;
53 }
54
55 ret = fcntl(pipefd[1], F_GETFD);
56 if (ret == -1) {
57 usbi_err(NULL, "failed to get pipe fd flags (%d)", errno);
58 goto err_close_pipe;
59 }
60 ret = fcntl(pipefd[1], F_SETFD, ret | FD_CLOEXEC);
61 if (ret == -1) {
62 usbi_err(NULL, "failed to set pipe fd flags (%d)", errno);
63 goto err_close_pipe;
64 }
65 #endif
66
67 ret = fcntl(pipefd[1], F_GETFL);
68 if (ret == -1) {
69 usbi_err(NULL, "failed to get pipe fd status flags (%d)", errno);
70 goto err_close_pipe;
71 }
72 ret = fcntl(pipefd[1], F_SETFL, ret | O_NONBLOCK);
73 if (ret == -1) {
74 usbi_err(NULL, "failed to set pipe fd status flags (%d)", errno);
75 goto err_close_pipe;
76 }
77
78 return 0;
79
80 err_close_pipe:
81 close(pipefd[0]);
82 close(pipefd[1]);
83 return ret;
84 }
85