aboutsummaryrefslogtreecommitdiff
path: root/tests/compat/pipe2.c
blob: e2aaa28bb18071ac5295b320d07b8b85d7efcdae (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
/*
 * Public domain
 */

#include <fcntl.h>
#include <unistd.h>
#include <sys/socket.h>
#undef socketpair

static int setfd(int fd, int flag)
{
	int flags = fcntl(fd, F_GETFD);
	flags |= flag;
	return fcntl(fd, F_SETFD, flags);
}

static int setfl(int fd, int flag)
{
	int flags = fcntl(fd, F_GETFL);
	flags |= flag;
	return fcntl(fd, F_SETFL, flags);
}

int pipe2(int fildes[2], int flags)
{
	int rc = pipe(fildes);
	if (rc == 0) {
		if (flags & O_NONBLOCK) {
			setfl(fildes[0], O_NONBLOCK);
			setfl(fildes[1], O_NONBLOCK);
		}
		if (flags & O_CLOEXEC) {
			setfd(fildes[0], FD_CLOEXEC);
			setfd(fildes[1], FD_CLOEXEC);
		}
	}
	return rc;
}

int bsd_socketpair(int domain, int type, int protocol, int socket_vector[2])
{
	int flags = type & ~0xf;
	type &= 0xf;
	int rc = socketpair(domain, type, protocol, socket_vector);
	if (rc == 0) {
		if (flags & SOCK_NONBLOCK) {
			setfl(socket_vector[0], O_NONBLOCK);
			setfl(socket_vector[1], O_NONBLOCK);
		}
		if (flags & SOCK_CLOEXEC) {
			setfd(socket_vector[0], FD_CLOEXEC);
			setfd(socket_vector[1], FD_CLOEXEC);
		}
	}
	return rc;
}