SetConsoleCtrlHandler equivalent for Unix/Linux C+

2019-09-07 21:05发布

问题:

Does anybody know an equivalent of the Windows SetConsoleCtrlHandler function for Linux/UNIX OS? (Specifically, for a wxWidgets application.)

回答1:

You can use the 'signal()' function.

Here's an example:

#include <signal.h>

bool stop = false;

void app_stopped(int sig)
{
   // function called when signal is received.
   stop = true;
}

int main()
{
   // app_stopped will be called when SIGINT (Ctrl+C) is received.
   signal(SIGINT, app_stopped);

   while(false == stop)
      Sleep(10);
}

As mentioned in the comments, sigaction() avoids some pitfalls that can be common with signal(), and should be preferred..



标签: c++ linux winapi