-
Notifications
You must be signed in to change notification settings - Fork 1
/
pollinfd.c
102 lines (89 loc) · 2.22 KB
/
pollinfd.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
#include <errno.h>
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <poll.h>
#include <unistd.h>
static void
usage(void)
{
static char const message[] =
"Usage: pollinfd [-t timeout] fd [cmd] [args]...\n";
if (fputs(message, stderr) == EOF)
perror("fputs");
}
static bool
str2num(char const *const str, int const min, int const max,
int *const out, char const *const err)
{
char *endptr;
errno = 0;
long const longnum = strtol(str, &endptr, 10);
if (errno) {
perror("strtol");
return false;
}
if (endptr == str || longnum < min || longnum > max || *endptr) {
if (fputs(err, stderr) == EOF)
perror("fputs");
return false;
}
*out = (int)longnum;
return true;
}
int
main(int const argc, char **const argv)
{
int timeout = -1;
for (int opt; opt = getopt(argc, argv, "+t:"), opt != -1;) {
switch (opt) {
case 't': {
static const char etimeout[] = "Invalid timeout.\n";
if (!str2num(optarg, INT_MIN, INT_MAX, &timeout, etimeout))
return 2;
break;
}
default:
usage();
return 2;
}
}
if (argc <= optind) {
usage();
return 2;
}
char const *const argfd = argv[optind];
char **const command = &argv[optind + 1];
struct pollfd pollfd = {
.events = POLLIN,
};
if (!str2num(argfd, 0, INT_MAX, &pollfd.fd, "Invalid fd.\n"))
return 2;
do {
switch (poll(&pollfd, 1, timeout)) {
case 0:
return 1;
case -1:
if (errno == EINTR || errno == EAGAIN)
continue;
perror("poll");
return 2;
}
} while (0);
if (!(pollfd.revents & POLLIN)) {
if (pollfd.revents & POLLNVAL) {
static char const epollnval[] =
"File descriptor cannot be used with poll.\n";
if (fputs(epollnval, stderr) == EOF)
perror("fputs");
return 2;
}
return 1;
}
if (!*command)
return 0;
(void)execvp(*command, command);
perror("execvp");
return 2;
}