user-0 提问: 怎么使用sigsetjmp和signal来实现try-catch

回复:
user: user-1
content: 仅供参考：longjmp Restores stack environment and execution locale.  void longjmp( jmp_buf env, int value );  Routine Required Header Compatibility  longjmp <setjmp.h> ANSI, Win 95, Win NT    For additional compatibility information, see Compatibility in the Introduction.  Libraries  LIBC.LIB Single thread static library, retail version  LIBCMT.LIB Multithread static library, retail version  MSVCRT.LIB Import library for MSVCRT.DLL, retail version    Return Value  None  Parameters  env  Variable in which environment is stored  value  Value to be returned to setjmp call  Remarks  The longjmp function restores a stack environment and execution locale previously saved in env by setjmp. setjmp and longjmp provide a way to execute a nonlocal goto; they are typically used to pass execution control to error-handling or recovery code in a previously called routine without using the normal call and return conventions.  A call to setjmp causes the current stack environment to be saved in env. A subsequent call to longjmp restores the saved environment and returns control to the point immediately following the corresponding setjmp call. Execution resumes as if value had just been returned by the setjmp call. The values of all variables (except register variables) that are accessible to the routine receiving control contain the values they had when longjmp was called. The values of register variables are unpredictable. The value returned by setjmp must be nonzero. If value is passed as 0, the value 1 is substituted in the actual return.  Call longjmp before the function that called setjmp returns; otherwise the results are unpredictable.  Observe the following restrictions when using longjmp:   Do not assume that the values of the register variables will remain the same. The values of register variables in the routine calling setjmp may not be restored to the proper values after longjmp is executed.    Do not use longjmp to transfer control out of an interrupt-handling routine unless the interrupt is caused by a floating-point exception. In this case, a program may return from an interrupt handler via longjmp if it first reinitializes the floating-point math package by calling _fpreset.   Be careful when using setjmp and longjmp in C++ programs. Because these functions do not support C++ object semantics, it is safer to use the C++ exception-handling mechanism.  Example  /* FPRESET.C: This program uses signal to set up a  * routine for handling floating-point errors.  */  #include <stdio.h> #include <signal.h> #include <setjmp.h> #include <stdlib.h> #include <float.h> #include <math.h> #include <string.h>  jmp_buf mark;              /* Address for long jump to jump to */ int     fperr;             /* Global error number */  void __cdecl fphandler( int sig, int num );   /* Prototypes */ void fpcheck( void );  void main( void ) {    double n1, n2, r;    int jmpret;    /* Unmask all floating-point exceptions. */     _control87( 0, _MCW_EM );    /* Set up floating-point error handler. The compiler     * will generate a warning because it expects     * signal-handling functions to take only one argument.     */     if( signal( SIGFPE, fphandler ) == SIG_ERR )     {       fprintf( stderr, "Couldn't set SIGFPE\n" );       abort();   }     /* Save stack environment for return in case of error. First      * time through, jmpret is 0, so true conditional is executed.      * If an error occurs, jmpret will be set to -1 and false      * conditional will be executed.     */    jmpret = setjmp( mark );    if( jmpret == 0 )    {       printf( "Test for invalid operation - " );       printf( "enter two numbers: " );       scanf( "%lf %lf", &n1, &n2 );       r = n1 / n2;       /* This won't be reached if error occurs. */       printf( "\n\n%4.3g / %4.3g = %4.3g\n", n1, n2, r );        r = n1 * n2;       /* This won't be reached if error occurs. */       printf( "\n\n%4.3g * %4.3g = %4.3g\n", n1, n2, r );    }    else       fpcheck(); } /* fphandler handles SIGFPE (floating-point error) interrupt. Note  * that this prototype accepts two arguments and that the   * prototype for signal in the run-time library expects a signal   * handler to have only one argument.  *  * The second argument in this signal handler allows processing of  * _FPE_INVALID, _FPE_OVERFLOW, _FPE_UNDERFLOW, and   * _FPE_ZERODIVIDE, all of which are Microsoft-specific symbols   * that augment the information provided by SIGFPE. The compiler   * will generate a warning, which is harmless and expected.   */ void fphandler( int sig, int num ) {    /* Set global for outside check since we don't want     * to do I/O in the handler.     */    fperr = num;    /* Initialize floating-point package. */    _fpreset();    /* Restore calling environment and jump back to setjmp. Return      * -1 so that setjmp will return false for conditional test.     */    longjmp( mark, -1 ); } void fpcheck( void ) {    char fpstr[30];    switch( fperr )    {    case _FPE_INVALID:        strcpy( fpstr, "Invalid number" );        break;    case _FPE_OVERFLOW:        strcpy( fpstr, "Overflow" );         break;    case _FPE_UNDERFLOW:        strcpy( fpstr, "Underflow" );        break;    case _FPE_ZERODIVIDE:        strcpy( fpstr, "Divide by zero" );        break;    default:        strcpy( fpstr, "Other floating point error" );        break;    }    printf( "Error %d: %s\n", fperr, fpstr ); }   Output  Test for invalid operation - enter two numbers: 5 0 Error 131: Divide by zero   Process and Environment Control Routines  See Also   setjmp

user: user-0
content: 引用 1 楼 zhao4zhong1 的回复:个人意见： 实现再多的try-catch，也不如学会分析dump文件。 会分析再多的dump文件，也不如学会设置数据改变断点， 设置再多的数据改变断点，也不如学会写日志到文件。  有时不将“调用函数名字＋各参数值，进入函数后各参数值，中间变量值，退出函数前准备返回的值，返回函数到调用处后函数名字＋各参数值＋返回值”这些信息写日志到文件中是无论如何也发现不了问题在哪里的，包括捕获各种异常、写日志到屏幕、单步或设断点或生成core文件、……这些方法都不行！ 写日志到文件参考下面： #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef WIN32     #include <windows.h>     #include <io.h> #else     #include <unistd.h>     #include <sys/time.h>     #include <pthread.h>     #define  CRITICAL_SECTION   pthread_mutex_t     #define  _vsnprintf         vsnprintf #endif //Log{ #define MAXLOGSIZE 20000000 #define MAXLINSIZE 16000 #include <time.h> #include <sys/timeb.h> #include <stdarg.h> char logfilename1[]="MyLog1.log"; char logfilename2[]="MyLog2.log"; static char logstr[MAXLINSIZE+1]; char datestr[16]; char timestr[16]; char mss[4]; CRITICAL_SECTION cs_log; FILE *flog; #ifdef WIN32 void Lock(CRITICAL_SECTION *l) {     EnterCriticalSection(l); } void Unlock(CRITICAL_SECTION *l) {     LeaveCriticalSection(l); } #else void Lock(CRITICAL_SECTION *l) {     pthread_mutex_lock(l); } void Unlock(CRITICAL_SECTION *l) {     pthread_mutex_unlock(l); } #endif void LogV(const char *pszFmt,va_list argp) {     struct tm *now;     struct timeb tb;      if (NULL==pszFmt||0==pszFmt[0]) return;     _vsnprintf(logstr,MAXLINSIZE,pszFmt,argp);     ftime(&tb);     now=localtime(&tb.time);     sprintf(datestr,"%04d-%02d-%02d",now->tm_year+1900,now->tm_mon+1,now->tm_mday);     sprintf(timestr,"%02d:%02d:%02d",now->tm_hour     ,now->tm_min  ,now->tm_sec );     sprintf(mss,"%03d",tb.millitm);     printf("%s %s.%s %s",datestr,timestr,mss,logstr);     flog=fopen(logfilename1,"a");     if (NULL!=flog) {         fprintf(flog,"%s %s.%s %s",datestr,timestr,mss,logstr);         if (ftell(flog)>MAXLOGSIZE) {             fclose(flog);             if (rename(logfilename1,logfilename2)) {                 remove(logfilename2);                 rename(logfilename1,logfilename2);             }         } else {             fclose(flog);         }     } } void Log(const char *pszFmt,...) {     va_list argp;      Lock(&cs_log);     va_start(argp,pszFmt);     LogV(pszFmt,argp);     va_end(argp);     Unlock(&cs_log); } //Log} int main(int argc,char * argv[]) {     int i; #ifdef WIN32     InitializeCriticalSection(&cs_log); #else     pthread_mutex_init(&cs_log,NULL); #endif     for (i=0;i<10000;i++) {         Log("This is a Log %04d from FILE:%s LINE:%d\n",i, __FILE__, __LINE__);     } #ifdef WIN32     DeleteCriticalSection(&cs_log); #else     pthread_mutex_destroy(&cs_log); #endif     return 0; } //1-78行添加到你带main的.c或.cpp的那个文件的最前面 //81-85行添加到你的main函数开头 //89-93行添加到你的main函数结束前 //在要写LOG的地方仿照第87行的写法写LOG到文件MyLog1.log中  但是老师要求我们实现。。。

user: user-1
content: 个人意见： 实现再多的try-catch，也不如学会分析dump文件。 会分析再多的dump文件，也不如学会设置数据改变断点， 设置再多的数据改变断点，也不如学会写日志到文件。  有时不将“调用函数名字＋各参数值，进入函数后各参数值，中间变量值，退出函数前准备返回的值，返回函数到调用处后函数名字＋各参数值＋返回值”这些信息写日志到文件中是无论如何也发现不了问题在哪里的，包括捕获各种异常、写日志到屏幕、单步或设断点或生成core文件、……这些方法都不行！ 写日志到文件参考下面： #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef WIN32     #include <windows.h>     #include <io.h> #else     #include <unistd.h>     #include <sys/time.h>     #include <pthread.h>     #define  CRITICAL_SECTION   pthread_mutex_t     #define  _vsnprintf         vsnprintf #endif //Log{ #define MAXLOGSIZE 20000000 #define MAXLINSIZE 16000 #include <time.h> #include <sys/timeb.h> #include <stdarg.h> char logfilename1[]="MyLog1.log"; char logfilename2[]="MyLog2.log"; static char logstr[MAXLINSIZE+1]; char datestr[16]; char timestr[16]; char mss[4]; CRITICAL_SECTION cs_log; FILE *flog; #ifdef WIN32 void Lock(CRITICAL_SECTION *l) {     EnterCriticalSection(l); } void Unlock(CRITICAL_SECTION *l) {     LeaveCriticalSection(l); } #else void Lock(CRITICAL_SECTION *l) {     pthread_mutex_lock(l); } void Unlock(CRITICAL_SECTION *l) {     pthread_mutex_unlock(l); } #endif void LogV(const char *pszFmt,va_list argp) {     struct tm *now;     struct timeb tb;      if (NULL==pszFmt||0==pszFmt[0]) return;     _vsnprintf(logstr,MAXLINSIZE,pszFmt,argp);     ftime(&tb);     now=localtime(&tb.time);     sprintf(datestr,"%04d-%02d-%02d",now->tm_year+1900,now->tm_mon+1,now->tm_mday);     sprintf(timestr,"%02d:%02d:%02d",now->tm_hour     ,now->tm_min  ,now->tm_sec );     sprintf(mss,"%03d",tb.millitm);     printf("%s %s.%s %s",datestr,timestr,mss,logstr);     flog=fopen(logfilename1,"a");     if (NULL!=flog) {         fprintf(flog,"%s %s.%s %s",datestr,timestr,mss,logstr);         if (ftell(flog)>MAXLOGSIZE) {             fclose(flog);             if (rename(logfilename1,logfilename2)) {                 remove(logfilename2);                 rename(logfilename1,logfilename2);             }         } else {             fclose(flog);         }     } } void Log(const char *pszFmt,...) {     va_list argp;      Lock(&cs_log);     va_start(argp,pszFmt);     LogV(pszFmt,argp);     va_end(argp);     Unlock(&cs_log); } //Log} int main(int argc,char * argv[]) {     int i; #ifdef WIN32     InitializeCriticalSection(&cs_log); #else     pthread_mutex_init(&cs_log,NULL); #endif     for (i=0;i<10000;i++) {         Log("This is a Log %04d from FILE:%s LINE:%d\n",i, __FILE__, __LINE__);     } #ifdef WIN32     DeleteCriticalSection(&cs_log); #else     pthread_mutex_destroy(&cs_log); #endif     return 0; } //1-78行添加到你带main的.c或.cpp的那个文件的最前面 //81-85行添加到你的main函数开头 //89-93行添加到你的main函数结束前 //在要写LOG的地方仿照第87行的写法写LOG到文件MyLog1.log中