donniebreve / touchcursor-linux

TouchCursor style keyboard remapping for Linux.
GNU General Public License v2.0
133 stars 28 forks source link

Detect signals and perform appropriate actions #55

Closed donniebreve closed 1 year ago

donniebreve commented 2 years ago

If you restart the service, it will continue to create new virtual output devices.

https://www.geeksforgeeks.org/signals-c-language/

auouymous commented 2 years ago

Here is code to register signal handlers. The handler itself should do very little, set a flag and return, without allocating any memory or calling functions which might allocate memory. The main loop would then detect the flag, remove the device and terminate. TERM and INT could call the same handler and terminate the process, while HUP could reset any state and reload config file.

You can exit directly from the handler but I don't know how safe it would be to remove the device in it. That may be the only option if the main loop can't easily be woken. It might sometimes crash and not remove the device, but work correctly other times.

#include <signal.h>

static void SIG*_handler( int signal ){
  ...
}

int main( int argc, char *argv[] ){
  ...

  // create stack for signal handlers
  const int ss_size = 4*4096;
  stack_t sigstack;
  sigstack.ss_sp = malloc(ss_size);
  sigstack.ss_size = ss_size;
  sigstack.ss_flags = 0;
  sigaltstack(&sigstack, NULL);

  struct sigaction act;
  memset(&act, 0, sizeof(struct sigaction));
  act.sa_flags = SA_ONSTACK;

  act.sa_handler = SIGHUP_handler; sigaction(SIGHUP, &act, NULL);
  act.sa_handler = SIGINT_handler; sigaction(SIGINT, &act, NULL);
  act.sa_handler = SIGTERM_handler; sigaction(SIGTERM, &act, NULL);

  ...
}