【发布时间】:2017-08-30 10:52:20
【问题描述】:
与How can I handle interrupt signal and call destructor in c++? 相关,但我的问题围绕着构建程序。
我正在编写一个模拟程序,将数据写入 HDF5 文件。但是在程序中断的情况下,我希望 HDF5 能够正确关闭,以便累积的数据仍然可以读取。我编写了一个包含 HDF5 文件句柄的 HDF5 编写器类,如果调用该类的析构函数,则 HDF5 文件应该关闭。因此,如果 Ctrl-C 中断程序,我想捕获 SIGINT,并调用析构函数。
根据我的阅读,包括Is destructor called if SIGINT or SIGSTP issued?,sigaction 的处理函数应该很简单,无非就是改变一个标志。这导致了一个类似于以下的程序(从第二个链接复制)...
#include <iostream>
#include <signal.h>
#include <unistd.h>
#include <cstring>
#include <atomic>
std::atomic<bool> quit(false); // signal flag
void got_signal(int)
{
quit.store(true);
}
class Foo
{
public:
~Foo() { std::cout << "destructor\n"; }
};
int main(void)
{
struct sigaction sa;
memset( &sa, 0, sizeof(sa) );
sa.sa_handler = got_signal;
sigfillset(&sa.sa_mask);
sigaction(SIGINT,&sa,NULL);
Foo foo; // needs destruction before exit
while (true)
{
// do real work here...
sleep(1);
if( quit.load() ) break; // exit normally after SIGINT
}
return 0;
}
您可以在程序结构中看到while 循环中的部分应该足够短,以便程序经常检查标志quit。但我的问题是我的程序结构更像这样:
int main()
{
// set up variables
HDF5Writer writer(...);
run_simulation(&writer, [params]);
}
run_simulation 将运行我的模拟,直到满足指定的停止条件,这可能需要几分钟/几小时。如何设置我的程序来监控一些标志,以便它在及时收到 SIGINT 后关闭?
【问题讨论】:
-
你总是可以像这样抛出异常(虽然它不是真正可移植的):stackoverflow.com/a/5861669/2097780
-
然后我可以尝试将
run_simulation放入尝试中,但要捕获异常的块除外?我只需要在 linux 上运行的东西 -
是的!你也需要使用
-fnon-call-exceptions编译你的代码。