]> git.meshlink.io Git - catta/blob - src/fdutil.c
work around lack of fcntl on Windows
[catta] / src / fdutil.c
1 /***
2   This file is part of catta.
3
4   catta is free software; you can redistribute it and/or modify it
5   under the terms of the GNU Lesser General Public License as
6   published by the Free Software Foundation; either version 2.1 of the
7   License, or (at your option) any later version.
8
9   catta is distributed in the hope that it will be useful, but WITHOUT
10   ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11   or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
12   Public License for more details.
13
14   You should have received a copy of the GNU Lesser General Public
15   License along with catta; if not, write to the Free Software
16   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
17   USA.
18 ***/
19
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
23
24 #include <sys/select.h>
25 #include <unistd.h>
26 #include <assert.h>
27
28 #ifdef HAVE_FCNTL
29 #include <fcntl.h>
30 #else
31 #include <sys/ioctl.h>
32 #endif
33
34 #include "fdutil.h"
35
36 int catta_set_cloexec(int fd) {
37     int n;
38
39     assert(fd >= 0);
40
41 #if defined(HAVE_FCNTL)
42     if ((n = fcntl(fd, F_GETFD)) < 0)
43         return -1;
44
45     if (n & FD_CLOEXEC)
46         return 0;
47
48     return fcntl(fd, F_SETFD, n|FD_CLOEXEC);
49 #elif defined(_WIN32)
50     (void)n;
51     if(!SetHandleInformation((HANDLE)fd, HANDLE_FLAG_INHERIT, 0))
52         return -1;
53     return 0;
54 #else
55     (void)n;
56     return -1;
57 #endif
58 }
59
60 int catta_set_nonblock(int fd) {
61     int n;
62
63     assert(fd >= 0);
64
65 #ifdef HAVE_FCNTL
66     if ((n = fcntl(fd, F_GETFL)) < 0)
67         return -1;
68
69     if (n & O_NONBLOCK)
70         return 0;
71
72     return fcntl(fd, F_SETFL, n|O_NONBLOCK);
73 #else
74     n = 1;
75     return ioctl(fd, FIONBIO, &n);
76 #endif
77 }
78
79 int catta_wait_for_write(int fd) {
80     fd_set fds;
81     int r;
82
83     FD_ZERO(&fds);
84     FD_SET(fd, &fds);
85
86     if ((r = select(fd+1, NULL, &fds, NULL, NULL)) < 0)
87         return -1;
88
89     assert(r > 0);
90
91     return 0;
92 }