I need my command line application to wait for Ctrl-C in the main thread and then execute some deinitialization code and exit.
I tested this scenario with the following test program:
#include <unistd.h>
#include <signal.h>
#include <cstdlib>
#include <cstdio>
#include <cassert>
using namespace std;
void control_break_handler(int) { printf("\ncontrol_break_handler\n"); }
int main()
{
printf("%s", "Before signal\n");
int result = 0;
struct sigaction sigact = {};
result = sigemptyset(&sigact.sa_mask);
assert(result == 0);
sigact.sa_handler = &control_break_handler;
sigact.sa_flags = 0;
result = sigaction(SIGINT, &sigact, NULL);
assert(result == 0);
sigset_t set;
result = sigemptyset(&set);
assert(result == 0);
result = sigaddset(&set, SIGINT);
assert(result == 0);
int sig;
result = sigwait(&set, &sig);
assert(result == 0);
printf("\nsigwait returned %d, sig = %d\n", result, sig);
sleep(10);
return 0;
}
But it just prints
sigwait returned 0, sig = 2
after first Ctrl-C and the "control_break_handler" called only after the second Ctrl-C. How do I execute deinitialization code on first Ctrl-C? I use Ubuntu 13.04 x64.
EDIT: Ok, it seems I figured this out. I thrown away sigaction
and added call to sigprocmask
before sigwait
. It seems to work just fine.