Handling the SIGINT interrupt signal

Jun 25, 2010 at 2:22am
Hey guys. My program does long runs, and generates too much data to store as it goes along. It typically saves the info at the end, when it's done. However, sometimes we decide that it has run enough in the middle, and kill it. But then we lose all the data.

How can I handle SIGINT so that I can at least dump the data I have so far to a file?

Thanks!
Jun 25, 2010 at 8:06am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <csignal>
#include <iostream>
using namespace std;

// SIGINT handler
void int_handler(int x)
{
cout <<"In interruot handler"<<endl; // after pressing CTRL+C you'll see this message

}


int main()
{
signal(SIGINT,int_handler);

cout <<"Press ctrl+c now\n";
cin.get();
}


http://www.cplusplus.com/reference/clibrary/csignal/
http://www.cplusplus.com/reference/clibrary/csignal/signal/
Jun 25, 2010 at 10:13am
You should only set a flag in an interrupt handler and then check this flag in the code part that you use to parse/calculate your data.

You should also avoid printing messages from signal handlers since printf and cout are not reentrant.
Jun 26, 2010 at 9:58pm
Thanks Null, I'll take a look at that.

And can we get an IP ban for this fucker? ^^
Topic archived. No new replies allowed.