Hi all,

I'm trying to catch signals and user interrupts in my application to
perform some cleanup, but having trouble getting this to work on MSYS2 (up
to date as of this morning). To get to the bottom of this, I've written
this minimal (not) working example:

#include <windows.h>
#include <wincon.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>

// WIN32 Ctrl handler:
BOOL WINAPI CtrlHandler (DWORD CtrlType)
  if (CtrlType == CTRL_C_EVENT) {
    fprintf (stderr, "caught Ctrl-C (via CtrlHandler)\n");
  fprintf (stderr, "caught something else (via CtrlHandler)\n");
  return true;

// POSIX signal handler:
void signal_handler (int sig)
  if (sig == SIGINT) {
    fprintf (stderr, "caught Ctrl-C (via signal_handler)\n");
    exit (0);
  fprintf (stderr, "caught something else (via signal_handler)\n");
  exit (0);

int main (int argc, char* argv[])
  // avoid buffering on stderr:
  setvbuf(stderr, NULL, _IONBF, 0);

  // set Windows Ctrl handler:
  SetConsoleCtrlHandler (CtrlHandler, true);

  // set POSIX signal handler:
  signal (SIGINT, signal_handler);

  /* the following does not compile:

  // set signal handler via sigaction():
  struct sigaction act;
  act.sa_handler = &signal_handler;
  sigfillset (&act.sa_mask);
  act.sa_flags = 0;
  sigaction (SIGINT, &act, NULL);


  // twiddle your thumbs until the user presses Ctrl-C:
  while (1) {
    fprintf (stderr, "- tick -\n");
    sleep (1);

  return 0;

which I compile and run with:

$ gcc catch_ctrl-c.cpp -o catch_ctrl-c && ./catch_ctrl-c.exe
- tick -
- tick -


In the above, I hit Ctrl-C after the second tick, but neither handler was
invoked. You'll also note I tried the sigaction() version too (what we use
on Linux, as recommended on the manpage), but if I uncomment this section,
it fails to compile on MSYS2, with the following error:
catch_ctrl-c.cpp: In function 'int main(int, char**)':
catch_ctrl-c.cpp:46:20: error: aggregate 'main(int, char**)::sigaction act'
has incomplete type and cannot be defined
   struct sigaction act;
catch_ctrl-c.cpp:48:27: error: 'sigfillset' was not declared in this scope
   sigfillset (&act.sa_mask);
catch_ctrl-c.cpp:50:32: error: invalid use of incomplete type 'struct
main(int, char**)::sigaction'
   sigaction (SIGINT, &act, NULL);
catch_ctrl-c.cpp:46:10: note: forward declaration of 'struct main(int,
   struct sigaction act;

Also tested with clang, same result. Does anyone know how to get this to
work in MSYS2?


*Dr J-Donald Tournier (PhD)*

*Senior Lecturer, **Biomedical Engineering*

*Division of Imaging Sciences & Biomedical EngineeringKing's College London*

*A: Department of Perinatal Imaging & Health, 1st Floor South Wing, St
Thomas' Hospital, London. SE1 7EH*
*T: +44 (0)20 7188 7118 ext 53613*
Msys2-users mailing list

Reply via email to