检测程序终止(C,Windows中) [英] detect program termination (C, Windows)

查看:156
本文介绍了检测程序终止(C,Windows中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有了它完成之前执行某些任务的程序。问题是,有时与例外的程序崩溃(如数据库不能达到,等等)。
现在,有没有什么办法来检测异常终止,并执行一些code它死之前?

I have a program that has to perform certain tasks before it finishes. The problem is that sometimes the program crashes with an exception (like database cannot be reached, etc). Now, is there any way to detect an abnormal termination and execute some code before it dies?

感谢。

code是AP preciated。

code is appreciated.

推荐答案

1。 Win32的

Win32 API可以包含一个方式通过<一个做到这一点href=\"http://msdn.microsoft.com/en-us/library/ms680634%28VS.85%29.aspx\">SetUnhandledExceptionFilter函数,如下所示:

The Win32 API contains a way to do this via the SetUnhandledExceptionFilter function, as follows:

LONG myFunc(LPEXCEPTION_POINTERS p)
{
     printf("Exception!!!\n");     
     return EXCEPTION_EXECUTE_HANDLER;
}

int main()
{
     SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)&myFunc);    
     // generate an exception !
     int x = 0;
     int y = 1/x;
     return 0;
}

2。 POSIX / Linux的

我通常通过信号()函数做到这一点,然后适当地处理SIGSEGV信号。您也可以处理SIGTERM信号和SIGINT,而不是SIGKILL(设计)。您可以使用 strace的()得到一个回溯,看看什么引起的信号。

I usually do this via the signal() function and then handle the SIGSEGV signal appropriately. You can also handle the SIGTERM signal and SIGINT, but not SIGKILL (by design). You can use strace() to get a backtrace to see what caused the signal.

这篇关于检测程序终止(C,Windows中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆