summaryrefslogtreecommitdiff
path: root/src/platform/posix/posix_pipe.c
blob: bc42abec99e89b1cc345fdf8052904b061f014a2 (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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
//
// Copyright 2017 Garrett D'Amore <garrett@damore.org>
//
// This software is supplied under the terms of the MIT License, a
// copy of which should be located in the distribution where this
// file was obtained (LICENSE.txt).  A copy of the license may also be
// found online at https://opensource.org/licenses/MIT.
//

// POSIX pipes.
#include "core/nng_impl.h"

#ifdef NNG_PLATFORM_POSIX

#include <errno.h>

// This implementation of notification pipes works ~everywhere on POSIX,
// as it only relies on pipe() and non-blocking I/O.

#ifdef NNG_USE_EVENTFD

// Linux eventfd.  This is lighter weight than pipes, and has better semantics
// to boot.  This is far better than say epoll().
#include <fcntl.h>
#include <sys/eventfd.h>
#include <unistd.h>

#ifdef EFD_CLOEXEC
#define NNI_EVENTFD_FLAGS EFD_CLOEXEC
#else
#define NNI_EVENTFD_FLAGS 0
#endif

int
nni_plat_pipe_open(int *wfd, int *rfd)
{
	int fd;

	if ((fd = eventfd(0, NNI_EVENTFD_FLAGS)) < 0) {
		return (nni_plat_errno(errno));
	}
	(void) fcntl(fd, F_SETFD, FD_CLOEXEC);
	(void) fcntl(fd, F_SETFL, O_NONBLOCK);

	*wfd = *rfd = fd;
	return (0);
}

void
nni_plat_pipe_raise(int wfd)
{
	uint64_t one = 1;

	(void) write(wfd, &one, sizeof(one));
}

void
nni_plat_pipe_clear(int rfd)
{
	uint64_t val;

	(void) read(rfd, &val, sizeof(val));
}

void
nni_plat_pipe_close(int wfd, int rfd)
{
	NNI_ASSERT(wfd == rfd);
	(void) close(wfd);
}

#else // NNG_USE_EVENTFD

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

int
nni_plat_pipe_open(int *wfd, int *rfd)
{
	int fds[2];

	if (pipe(fds) < 0) {
		return (nni_plat_errno(errno));
	}
	*wfd = fds[1];
	*rfd = fds[0];

	(void) fcntl(fds[0], F_SETFD, FD_CLOEXEC);
	(void) fcntl(fds[1], F_SETFD, FD_CLOEXEC);
	(void) fcntl(fds[0], F_SETFL, O_NONBLOCK);
	(void) fcntl(fds[1], F_SETFL, O_NONBLOCK);

	return (0);
}

void
nni_plat_pipe_raise(int wfd)
{
	char c = 1;

	(void) write(wfd, &c, 1);
}

void
nni_plat_pipe_clear(int rfd)
{
	char buf[32];

	for (;;) {
		// Completely drain the pipe, but don't wait.  This coalesces
		// events somewhat.
		if (read(rfd, buf, sizeof(buf)) <= 0) {
			return;
		}
	}
}

void
nni_plat_pipe_close(int wfd, int rfd)
{
	close(wfd);
	close(rfd);
}

#endif // NNG_USE_EVENTFD

#endif // NNG_PLATFORM_POSIX