Skip to content

Commit 66e7992

Browse files
committed
add signal handling
1 parent 739e126 commit 66e7992

File tree

1 file changed

+22
-5
lines changed

1 file changed

+22
-5
lines changed

next/src/xcapture.c

+22-5
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,23 @@
66
#include <stdio.h>
77
#include <unistd.h>
88
#include <pwd.h>
9+
#include <time.h>
10+
#include <locale.h>
11+
#include <signal.h>
912
#include <bpf/bpf.h>
1013
#include "xcapture.h"
1114
#include "xcapture.skel.h"
1215
#include <syscall_names.h>
13-
#include <time.h>
14-
#include <locale.h>
16+
17+
18+
// handle CTRL+C and sigpipe etc
19+
static volatile bool exiting = false;
20+
21+
static void sig_handler(int sig)
22+
{
23+
exiting = true;
24+
}
25+
1526

1627
// translate uid to user name
1728
const char *getusername(uid_t uid)
@@ -91,6 +102,12 @@ int main(int argc, char **argv)
91102
ssize_t ret = 0;
92103
int err = 0;
93104

105+
/* Signal handling */
106+
signal(SIGINT, sig_handler);
107+
signal(SIGTERM, sig_handler);
108+
signal(SIGPIPE, sig_handler);
109+
110+
94111
/* For number formatting for readability */
95112
setlocale(LC_ALL,"en_US.UTF-8");
96113

@@ -115,7 +132,7 @@ int main(int argc, char **argv)
115132
bool header_printed = false;
116133

117134
// sample and print every second
118-
while (true) {
135+
while (!exiting) {
119136
clock_gettime(CLOCK_REALTIME, &sample_ts);
120137
// clock_gettime(CLOCK_MONOTONIC, &ktime); // TODO check twice and pick lowest diff in case of an interrupt/inv ctx switch
121138

@@ -225,10 +242,10 @@ int main(int argc, char **argv)
225242

226243
// sleep for 1 second for now (even if prev sample took some time)
227244
// TODO sleep N microseconds less, based on how long the last sample took (like in original v1 xcapture.c)
228-
usleep(1000000);
245+
if (!exiting)
246+
usleep(1000000);
229247
}
230248

231-
232249
cleanup:
233250
/* Clean up */
234251
fflush(stdout);

0 commit comments

Comments
 (0)