From 54f76b97d21b1198916cc354a6a5f7300c2eadc1 Mon Sep 17 00:00:00 2001 From: Kim Alvefur Date: Sat, 24 Feb 2024 00:05:29 +0100 Subject: util.signal: Add support for signalfd(2) on Linux signalfd allows handling signal events using the same method as sockets, via file descriptors. Thus all signal dispatch can go through the same main event loop as everything else, removing need for thread-scary signal handling where execution would just jump to the signal handler regardless of the state of Lua, and needing to keep track of Lua states/threads. --- util-src/signal.c | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/util-src/signal.c b/util-src/signal.c index a55b6f87..3af80a73 100644 --- a/util-src/signal.c +++ b/util-src/signal.c @@ -32,6 +32,10 @@ #include #include +#ifdef __linux__ +#include +#include +#endif #include "lua.h" #include "lauxlib.h" @@ -368,11 +372,41 @@ static int l_kill(lua_State *L) { #endif +#ifdef __linux__ +static int l_signalfd(lua_State *L) { + sigset_t mask; + + sigemptyset(&mask); + sigaddset(&mask, luaL_checkinteger(L, 1)); + + sigprocmask(SIG_BLOCK, &mask, NULL); /* TODO check err */ + + lua_pushinteger(L, signalfd(-1, &mask, SFD_NONBLOCK)); + return 1; +} + +static int l_signalfd_read(lua_State *L) { + const int sigfd = luaL_checkinteger(L, 1); + struct signalfd_siginfo siginfo; + + if(read(sigfd, &siginfo, sizeof(siginfo)) < 0) { + return 0; + } + + lua_pushinteger(L, siginfo.ssi_signo); + return 1; +} +#endif + static const struct luaL_Reg lsignal_lib[] = { {"signal", l_signal}, {"raise", l_raise}, #if defined(__unix__) || defined(__APPLE__) {"kill", l_kill}, +#endif +#ifdef __linux__ + {"signalfd", l_signalfd}, + {"signalfd_read", l_signalfd_read}, #endif {NULL, NULL} }; -- cgit v1.2.3