11

終了スタックに置くatexit( fn );と、プログラムが終了したときに実行されます: return frommain()または via exit().

スタックから削除できますか?

なぜ私はこれをしたいのですか?

atexitsetjmpおよびを使用して、単純な try-catch メカニズムを試していましたlongjmpundo-atexit(fn);最後に登録された関数でしか機能しない場合でも、できれば完璧です。

編集:

モノセレスの提案に従って、独自のスタックを作成します...

現在、スタックは 1 つの例外キャッチャーでのみ機能します。

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();
}
4

2 に答える 2

14

Why not build your own stack that you call from a single atexit() function? That way you could manipulate the stack all you want.

于 2010-02-22T12:04:19.887 に答える
8

No, you cannot do it, but you can use global flag so your exit handler will be doing nothing if the flag is set.

Alternatively you can call _Exit() (C99) - it will perform normal exit procedure (close all open descriptors, send all needed signals and parent/children) but will not call exit handler.

于 2010-02-22T12:04:03.100 に答える