I'm running a long computation in Linux, and every now and then I save partial results. I'd like to prevent interruptions in the function that saves partial results: for example, if a user presses CTRL-C, I want the function to finish and then the program to stop running).
For example, in the following code, I want that each "Saving..." is followed by a "Done".
#include <iostream>
void save_result(int i) {
disable_interruptions(); // WHAT SHOULD I PUT HERE?
std::cout << "Saving...";
/* open some files, edit them depending on i, etc. */
std::cout << "Done\n";
enable_interruptions(); // WHAT SHOULD I PUT HERE?
}
int main() {
while(true) {
int i = 1; /* some long computation */
save_result(i);
}
}
What I tried:
- Use some properties of file atomicity. Unfortunately, I have to change many files in various places, and I cannot do all the updates at the same time.
- Copy the files, edit the copy, move back atomically to the original place. The files are huge, and it will take too much time.
Thanks to Homer512 for pointing me in the right direction. We can capture the actions that stop the program using a signal handler, and re-raise the signal after we finished our update. Code:
Other links: