-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloop.c
More file actions
77 lines (68 loc) · 1.52 KB
/
loop.c
File metadata and controls
77 lines (68 loc) · 1.52 KB
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
#include <assert.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <sys/wait.h>
#include "types.h"
#include "bpf.h"
int
loop(FILE *log, const struct bpf *bpf, const struct opts *opts)
{
unsigned cur;
int rs;
char err[256];
unsigned prev = 0;
assert(bpf);
assert(log);
assert(opts);
fprintf(log, "monitoring for packets on %s interface\n", opts->ifname);
while (1) {
(void)read(bpf->fd, bpf->buf, bpf->len); /* blocks until there are packets */
rs = bpf_gstats(bpf->fd, &cur, err, sizeof err);
if (rs) {
fprintf(stderr, "failed to get interface stats: %s\n", err);
return 1;
}
if (cur < prev) {
fprintf(log, "overflow detected\n");
prev = cur;
continue;
}
if (cur - prev < opts->count) {
continue;
}
pid_t pid;
fprintf(log, "packet count reached "
"(prev=%u cur=%u)\n", prev, cur);
prev = cur;
pid = fork();
if (pid == -1) {
perror("fork");
return 1;
}
else if (pid == 0) {
fprintf(log, "child process started\n");
(void)execve(opts->path, opts->argv, NULL);
perror("execve");
_exit(1);
}
else {
int status;
rs = waitpid(pid, &status, 0);
if (rs == -1) {
perror("waitpid");
return 1;
}
if (WIFSIGNALED(status)) {
int sig = WTERMSIG(status);
const char *desc = strsignal(sig);
fprintf(log, "child process terminated by signal: %d (%s)\n", sig, desc);
}
else {
fprintf(WEXITSTATUS(status) ? stderr : log,
"child process exited with exit code %d\n",
WEXITSTATUS(status));
}
}
}
}