2 * Copyright (C) 2015, 2016 "IoT.bzh"
3 * Author "Fulup Ar Foll"
4 * Author José Bollo <jose.bollo@iot.bzh>
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
26 #include <afb/afb-req-itf.h>
28 #include "afb-sig-handler.h"
29 #include "afb-thread.h"
32 static _Thread_local sigjmp_buf *error_handler;
34 static void on_signal_terminate (int signum)
36 ERROR("Terminating signal received %s", strsignal(signum));
40 static void on_signal_error(int signum)
44 // unlock signal to allow a new signal to come
45 if (error_handler != NULL) {
47 sigaddset(&sigset, signum);
48 sigprocmask(SIG_UNBLOCK, &sigset, 0);
49 longjmp(*error_handler, signum);
51 if (signum == SIGALRM)
53 ERROR("Unmonitored signal received %s", strsignal(signum));
57 static int install(void (*handler)(int), int *signals)
61 if (signal(*signals, handler) == SIG_ERR) {
62 ERROR("failed to install signal handler for signal %s", strsignal(*signals));
70 int afb_sig_handler_init()
72 static int sigerr[] = { SIGALRM, SIGSEGV, SIGFPE, 0 };
73 static int sigterm[] = { SIGINT, SIGABRT, 0 };
75 return (install(on_signal_error, sigerr) & install(on_signal_terminate, sigterm)) - 1;
78 int afb_sig_req(struct afb_req req, void (*callback)(struct afb_req req))
81 sigjmp_buf jmpbuf, *older;
83 older = error_handler;
84 signum = setjmp(jmpbuf);
86 afb_req_fail_f(req, "aborted", "signal %s(%d) caught", strsignal(signum), signum);
88 error_handler = &jmpbuf;
91 error_handler = older;
95 int afb_sig_req_timeout(struct afb_req req, void (*callback)(struct afb_req req), int timeout)
100 afb_thread_timer_arm(timeout);
101 rc = afb_sig_req(req, callback);
102 afb_thread_timer_disarm();
106 void afb_sig_monitor(void (*function)(int sig, void*), void *closure, int timeout)
109 sigjmp_buf jmpbuf, *older;
111 older = error_handler;
112 signum = setjmp(jmpbuf);
114 function(signum, closure);
117 error_handler = &jmpbuf;
119 afb_thread_timer_arm(timeout);
120 function(0, closure);
122 afb_thread_timer_disarm();
123 error_handler = older;