在C ++中,当被ctrl-c中断时,在死亡之前调用带有参数(信号编号除外)的函数 [英] In C++ when interrupted with ctrl-c call a function with arguments (other than signal number) before dying
问题描述
在程序终止之前,当我用ctrl-c中断时,我想在文件中写一些额外的行.但是该文件的位置不是硬编码的,因此除了正常的中断处理外,我还需要一些其他功能
I want to write a few extra lines to a file when interrupted with ctrl-c before the program dies. However the location of the file is not hard coded so I need something more than normal interrupt handling as explained here. What is the best way to do this?
动机:
我正在做时间相关的有限元模拟.有时,我忘记或错误估计了合理的tmax,并且仿真将花费很长时间才能完成,因此我用ctrl-c中断了它.但是,我仍然想使用到目前为止生成的数据.特别是,有一个xml文件,需要在模拟完成后添加几行以关闭标签.当然,可以手动执行此操作,但这很痛苦,因此,我尝试使其自动化.
Motivation:
I'm doing time dependent finite element simulations. Sometimes I forget or mis-estimate a reasonable tmax and the simulation would take a very long time to complete, so I interrupt it with ctrl-c. However I still want to use the data generated up to that point. In particular there's an xml file which needs a few lines appended after the simulation is finished to close the tags. Of course it's possible to do this by hand but it's a pain, so I'm try to automate it.
推荐答案
Based on the answer to "How can I catch a ctrl-c event? (C++)" we can install a signal handler that simply raises an exception. Then we can catch the exception and run whatever standard c++ code we like.
这是一个可行的示例:
#include <iostream>
#include <exception>
#include <signal.h>
#include <stdlib.h>
class InterruptException : public std::exception
{
public:
InterruptException(int s) : S(s) {}
int S;
};
void sig_to_exception(int s)
{
throw InterruptException(s);
}
int main()
{
// Taken from answer to "How can I catch a ctrl-c event? (C++)"
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = sig_to_exception;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction(SIGINT, &sigIntHandler, NULL);
try
{
std::cout << "Inside try" << std::endl;
// Do something with output so the loop doesn't get optimised out
double i = 0;
while(i < 1e30) {i++;} // loop until interrupted
std::cout << i << std::endl;
}
catch(InterruptException& e)
{
std::cout << "Write something to file" << std::endl;
std::cout << "Caught signal " << e.S << std::endl;
return 1;
}
return 0;
}
这种方法确实有至少一个缺点:尝试安装处理程序后,我们必须包装所有内容,否则中断信号将导致abort().
This approach does have at least one downside: we have to wrap everything after the handler is installed in a try, otherwise interrupt signals would cause an abort().
这篇关于在C ++中,当被ctrl-c中断时,在死亡之前调用带有参数(信号编号除外)的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!