summaryrefslogtreecommitdiff
path: root/libusb/os/poll_posix.c
blob: a2ad157e4992bbaed0145d426d126d8bba736174 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
 * poll_posix: poll compatibility wrapper for POSIX systems
 * Copyright © 2013 RealVNC Ltd.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 *
 */

#include <config.h>

#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>

#include "libusbi.h"

int usbi_pipe(int pipefd[2])
{
#if defined(HAVE_PIPE2)
	int ret = pipe2(pipefd, O_CLOEXEC);
#else
	int ret = pipe(pipefd);
#endif

	if (ret != 0) {
		usbi_err(NULL, "failed to create pipe, errno=%d", errno);
		return ret;
	}

#if !defined(HAVE_PIPE2) && defined(FD_CLOEXEC)
	ret = fcntl(pipefd[0], F_GETFD);
	if (ret == -1) {
		usbi_err(NULL, "failed to get pipe fd flags, errno=%d", errno);
		goto err_close_pipe;
	}
	ret = fcntl(pipefd[0], F_SETFD, ret | FD_CLOEXEC);
	if (ret == -1) {
		usbi_err(NULL, "failed to set pipe fd flags, errno=%d", errno);
		goto err_close_pipe;
	}

	ret = fcntl(pipefd[1], F_GETFD);
	if (ret == -1) {
		usbi_err(NULL, "failed to get pipe fd flags, errno=%d", errno);
		goto err_close_pipe;
	}
	ret = fcntl(pipefd[1], F_SETFD, ret | FD_CLOEXEC);
	if (ret == -1) {
		usbi_err(NULL, "failed to set pipe fd flags, errno=%d", errno);
		goto err_close_pipe;
	}
#endif

	ret = fcntl(pipefd[1], F_GETFL);
	if (ret == -1) {
		usbi_err(NULL, "failed to get pipe fd status flags, errno=%d", errno);
		goto err_close_pipe;
	}
	ret = fcntl(pipefd[1], F_SETFL, ret | O_NONBLOCK);
	if (ret == -1) {
		usbi_err(NULL, "failed to set pipe fd status flags, errno=%d", errno);
		goto err_close_pipe;
	}

	return 0;

err_close_pipe:
	close(pipefd[0]);
	close(pipefd[1]);
	return ret;
}