blob: 3c065e81431cee8b19cc1dabb1ce929f06e8373c [file] [log] [blame]
Pekka Paalanen51aaf642012-05-30 15:53:41 +03001/*
2 * Copyright © 2012 Collabora, Ltd.
3 *
4 * Permission to use, copy, modify, distribute, and sell this software and its
5 * documentation for any purpose is hereby granted without fee, provided that
6 * the above copyright notice appear in all copies and that both that copyright
7 * notice and this permission notice appear in supporting documentation, and
8 * that the name of the copyright holders not be used in advertising or
9 * publicity pertaining to distribution of the software without specific,
10 * written prior permission. The copyright holders make no representations
11 * about the suitability of this software for any purpose. It is provided "as
12 * is" without express or implied warranty.
13 *
14 * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
15 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
16 * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
17 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
18 * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
19 * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
20 * OF THIS SOFTWARE.
21 */
22
23#include <sys/types.h>
24#include <sys/socket.h>
25#include <unistd.h>
26#include <fcntl.h>
27#include <errno.h>
Pekka Paalanen647f2bf2012-05-30 15:53:43 +030028#include <sys/epoll.h>
Pekka Paalanen51aaf642012-05-30 15:53:41 +030029
30#include "os-compatibility.h"
31
32static int
33set_cloexec_or_close(int fd)
34{
35 long flags;
36
37 if (fd == -1)
38 return -1;
39
40 flags = fcntl(fd, F_GETFD);
41 if (flags == -1)
42 goto err;
43
44 if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1)
45 goto err;
46
47 return fd;
48
49err:
50 close(fd);
51 return -1;
52}
53
54int
55os_socketpair_cloexec(int domain, int type, int protocol, int *sv)
56{
57 int ret;
58
59#ifdef SOCK_CLOEXEC
60 ret = socketpair(domain, type | SOCK_CLOEXEC, protocol, sv);
61 if (ret == 0 || errno != EINVAL)
62 return ret;
63#endif
64
65 ret = socketpair(domain, type, protocol, sv);
66 if (ret < 0)
67 return ret;
68
69 sv[0] = set_cloexec_or_close(sv[0]);
70 sv[1] = set_cloexec_or_close(sv[1]);
71
72 if (sv[0] != -1 && sv[1] != -1)
73 return 0;
74
75 close(sv[0]);
76 close(sv[1]);
77 return -1;
78}
79
Pekka Paalanen647f2bf2012-05-30 15:53:43 +030080int
81os_epoll_create_cloexec(void)
82{
83 int fd;
84
85#ifdef EPOLL_CLOEXEC
86 fd = epoll_create1(EPOLL_CLOEXEC);
87 if (fd >= 0)
88 return fd;
89 if (errno != EINVAL)
90 return -1;
91#endif
92
93 fd = epoll_create(1);
94 return set_cloexec_or_close(fd);
95}