1 /*
2 * lws-minimal-http-server-eventlib-foreign
3 *
4 * Written in 2020 by Christian Fuchs <christian.fuchs@scs.ch>
5 *
6 * This file is made available under the Creative Commons CC0 1.0
7 * Universal Public Domain Dedication.
8 *
9 * The sdevent specific code
10 */
11
12 #include <libwebsockets.h>
13
14 #include <string.h>
15 #include <signal.h>
16
17 #include <systemd/sd-event.h>
18
19 #include "private.h"
20
21 static struct sd_event *sd_loop;
22 static sd_event_source *sd_timer;
23 static sd_event_source *sd_signal;
24
25 static int
timer_cb_sd(sd_event_source * source,uint64_t now,void * user)26 timer_cb_sd(sd_event_source *source, uint64_t now, void *user)
27 {
28 foreign_timer_service(sd_loop);
29
30 if (sd_timer) {
31 sd_event_source_set_time(sd_timer, now + 1000000);
32 sd_event_source_set_enabled(sd_timer, SD_EVENT_ON);
33 }
34
35 return 0;
36 }
37
38 static int
signal_cb_sd(sd_event_source * source,const struct signalfd_siginfo * si,void * user)39 signal_cb_sd(sd_event_source *source, const struct signalfd_siginfo *si,
40 void *user)
41 {
42 signal_cb((int)si->ssi_signo);
43 return 0;
44 }
45
46 static void
foreign_event_loop_init_and_run_libsdevent(void)47 foreign_event_loop_init_and_run_libsdevent(void)
48 {
49 uint64_t now;
50
51 /* we create and start our "foreign loop" */
52
53 sd_event_default(&sd_loop);
54 sd_event_add_signal(sd_loop, &sd_signal, SIGINT, signal_cb_sd, NULL);
55
56 sd_event_now(sd_loop, CLOCK_MONOTONIC, &now);
57 sd_event_add_time(sd_loop, &sd_timer, CLOCK_MONOTONIC, now,
58 (uint64_t) 1000, timer_cb_sd, NULL);
59
60 sd_event_loop(sd_loop);
61 }
62
63 static void
foreign_event_loop_stop_libsdevent(void)64 foreign_event_loop_stop_libsdevent(void)
65 {
66 sd_event_exit(sd_loop, 0);
67 }
68
69 static void
foreign_event_loop_cleanup_libsdevent(void)70 foreign_event_loop_cleanup_libsdevent(void)
71 {
72 sd_event_source_set_enabled(sd_timer, SD_EVENT_OFF);
73 sd_timer = sd_event_source_unref(sd_timer);
74
75 sd_event_source_set_enabled(sd_signal, SD_EVENT_OFF);
76 sd_signal = sd_event_source_unref(sd_signal);
77
78 sd_loop = sd_event_unref(sd_loop);
79 }
80
81 const struct ops ops_sdevent = {
82 foreign_event_loop_init_and_run_libsdevent,
83 foreign_event_loop_stop_libsdevent,
84 foreign_event_loop_cleanup_libsdevent
85 };
86
87