题
如果退出堆栈上我地方atexit( fn );
,它将得到执行时,程序退出:从main()
或经由exit()
返回
我可以从栈中删除它?
为什么我要做到这一点,你问?
我使用atexit
,setjmp
和longjmp
一个简单的try-catch机制的实验。这将只是完美的,如果我能undo-atexit(fn);
- 即使它会只为最后的注册功能工作
编辑:
继monoceres的建议,使我自己的堆栈...
在堆只有一个例外捕手适用于现在。
void (*_catchFn[10])() = {0,0,0,0,0,0,0,0,0,0};
void _catch(){
if ( _catchFn[0] != 0 ){
(_catchFn[0])();
}
}
void _addCatch( void (*fn)() ){
_catchFn[0]=fn;
}
void _remCatch( void (*fn)() ){
_catchFn[0]=0;
}
void test(){
jmp_buf env;
void catch(){ // we get here after an exit with a registered catch
longjmp(env,1); // return to the line marked except...
// that first will get the value 1
}
int first = setjmp( env); // ** return here **
fprintf( stderr , "test: After setjmp. first=%d\n" , first );
if( first == 0 ){ // try this code
_addCatch(catch); // register the catch function to 'catch' the exit
fprintf( stderr , "test: Before CHECK\n" );
// CHECK something and something bad happens and it exits
exit(1); // like this
fprintf( stderr , "test: After CHECK - THIS SHOULD NEVER BE SEEN AFTER AN EXCEPTION.\n" );
}else{
fprintf( stderr , "test: After longjmp return. first=%d\n" , first );
}
_remCatch( catch);
fprintf( stderr , "test: IT WORKED!\n");
exit(1); // exit again to see if we are safe
}
int main(){
atexit( _catch ); // register my global exception stack
test();
}
解决方案
为什么不建立自己的堆栈,你从一个单一的atexit()函数调用?你可以操纵堆栈方式,所有你想要的。
其他提示
不,你不能这样做,但你可以使用全局标志,以便您的退出处理程序会做什么,如果设置了标志。
另外,您可以拨打_Exit()
(C99) - 它将执行正常退出程序(关闭所有打开的描述符,将所有需要的信号和父母/子女),但不会调用exit处理程序
不隶属于 StackOverflow