help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Floating point exception handling


From: John V. Shahid
Subject: Floating point exception handling
Date: Thu, 14 Jun 2007 10:33:53 -0400

I wonder if anyone out there can point me to the right direction of how
I can handle Floating point exceptions. I need to trap the exception, so
that I can detect them as soon as they occur. 
Currently, I tried to enable traps using
"feenableexcept(FE_ALL_EXCEPT)", but the status word seems to be cleared
as soon as I got inside the signal handler (see code below). I'm not
sure if this is a bug or if I need to "issue a floating point
instruction in order to force the kernel to restore the floating point
processor status."

Here is a sample of what I'm basically trying to do:

#include <stdio.h>
#include <fenv.h>
#include <signal.h>
#define printIfSet(status, x) if(status & x) printf(#x " was set.\n");
static void FPExceptionHandler(int signalNumber);
int main(int argc, char* argv[])
{
        /*
                Initialization code......
        */
    feclearexcept(FE_ALL_EXCEPT);/* make sure we have a clean start */
    feenableexcept(FE_ALL_EXCEPT);/* enable the traps for all excepts.*/
    signal(SIGFPE, FPExceptionHandler);
        /*
                Call a function that will cause an exception.
                The reason of the exception is unknown and that's why I
                need the traps in the first place.
        */
}
static void FPExceptionHandler(int signalNumber)
{
        /* Obtain the set of exceptions that were raised */
        /* Unfortunately, none of the flags are set */
    int result = fetestexcept(FE_ALL_EXCEPT);
    printf("Inside FP exception handler.\n");
        /* Print out which exception was raised */
    printIfSet(result, FE_INEXACT);
    printIfSet(result, FE_DIVBYZERO);
    printIfSet(result, FE_UNDERFLOW);
    printIfSet(result, FE_OVERFLOW);
    printIfSet(result, FE_INVALID);
        /* Revert back to the default action, and raise signal to
        terminate the program */
    signal(SIGFPE, SIG_DFL);
    raise(SIGFPE);
}

Also I've tried to use the extended BSD-like signal handler (i.e. the
signal handler with the extra parameter which contains a Bitwise-OR of
the exceptions which caused the trap), but the program couldn't compile
since the MACROS "FPE-FLTOVF-TRAP, etc" couldn't be found. The info
pages doesn't show where those MACROS are defined, so I assume they
should be in either signal.h or fenv.h





reply via email to

[Prev in Thread] Current Thread [Next in Thread]