-
Notifications
You must be signed in to change notification settings - Fork 1
/
airscan-pollable.c
116 lines (101 loc) · 1.89 KB
/
airscan-pollable.c
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
/* AirScan (a.k.a. eSCL) backend for SANE
*
* Copyright (C) 2019 and up by Alexander Pevzner ([email protected])
* See LICENSE for license terms and conditions
*
* Pollable events
*/
#include "airscan.h"
#ifdef OS_HAVE_EVENTFD
#include <sys/eventfd.h>
#endif
#include <poll.h>
#include <unistd.h>
#include <fcntl.h>
#pragma GCC diagnostic ignored "-Wunused-result"
/* The pollable event
*/
struct pollable {
int efd; /* Underlying eventfd handle */
#ifndef OS_HAVE_EVENTFD
// Without eventfd we use a pipe, so we need a second fd.
int write_fd;
#endif
};
/* Create new pollable event
*/
pollable*
pollable_new (void)
{
#ifdef OS_HAVE_EVENTFD
int efd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
#else
int fds[2];
int r = pipe2(fds, O_CLOEXEC | O_NONBLOCK);
int efd = r < 0 ? r : fds[0];
#endif
if (efd< 0) {
return NULL;
}
pollable *p = mem_new(pollable, 1);
p->efd = efd;
#ifndef OS_HAVE_EVENTFD
p->write_fd = fds[1];
#endif
return p;
}
/* Free pollable event
*/
void
pollable_free (pollable *p)
{
close(p->efd);
#ifndef OS_HAVE_EVENTFD
close(p->write_fd);
#endif
mem_free(p);
}
/* Get file descriptor for poll()/select().
*/
int
pollable_get_fd (pollable *p)
{
return p->efd;
}
/* Make pollable event "ready"
*/
void
pollable_signal (pollable *p)
{
static uint64_t c = 1;
#ifdef OS_HAVE_EVENTFD
write(p->efd, &c, sizeof(c));
#else
write(p->write_fd, &c, sizeof(c));
#endif
}
/* Make pollable event "not ready"
*/
void
pollable_reset (pollable *p)
{
uint64_t unused;
(void) read(p->efd, &unused, sizeof(unused));
}
/* Wait until pollable event is ready
*/
void
pollable_wait (pollable *p)
{
int rc;
do {
struct pollfd pfd = {
.fd = p->efd,
.events = POLLIN,
.revents = 0
};
rc = poll(&pfd, 1, -1);
} while (rc < 1);
}
/* vim:ts=8:sw=4:et
*/