Search code examples
cunixsignalsposixbsd

How to get further information on SIGFPE signal?


This is from The GNU C Library Reference Manual

int SIGFPE

The SIGFPE signal reports a fatal arithmetic error. This signal actually covers all arithmetic errors, including division by zero and overflow.

BSD systems provide the SIGFPE handler with an extra argument that distinguishes various causes of the exception. In order to access this argument, you must define the handler to accept two arguments, which means you must cast it to a one-argument function type in order to establish the handler.

But there is no example on how to access the extra argument.

I did my google work but could not find anything.

How can I get this extra information?


Solution

  • As EOF mentioned in the comments, the much better way to do this, that doesn't require formally broken casts, and a bonus is correctly documented, is to install your signal handler using sigaction and the SA_SIGINFO flag, and then in the si_code field of the second parameter (type siginfo_t) you can determine which floating-point error occurred:

    The following values can be placed in si_code for a SIGFPE signal:

    FPE_INTDIV Integer divide by zero.

    FPE_INTOVF Integer overflow.

    FPE_FLTDIV Floating-point divide by zero.

    FPE_FLTOVF Floating-point overflow.

    FPE_FLTUND Floating-point underflow.

    FPE_FLTRES Floating-point inexact result.

    FPE_FLTINV Floating-point invalid operation.

    FPE_FLTSUB Subscript out of range.

    Source: Linux sigaction(2) man page

    The same list is also readily available on the FreeBSD siginfo man page.