```
#include <fenv.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#define CNT_MAX 5
int cnt = 0;
void handler(int sig, siginfo_t *info, void *uap)
{
cnt++;
printf("Handler called %d times. Caught signal %d\n", cnt, sig);
printf("si_signo %d\n", info->si_signo);
printf("si_code %d\n", info->si_code);
printf("si_addr 0x%p\n", info->si_addr);
if (info->si_signo == SIGFPE &&
info->si_code == FPE_FLTDIV) {
printf("Caught SIGFPE due to FPE_FLTDIV, as expected\n");
} else
printf("Caught unexpected signal.\n");
printf("Clearing exceptions\n");
feclearexcept(FE_ALL_EXCEPT);
if (cnt >= CNT_MAX) {
printf("## handler called too many times, disabling FP exceptions ##\n");
fedisableexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW);
}
}
int main(void)
{
struct sigaction sa;
sa.sa_sigaction = handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_SIGINFO; /* Restart functions if
interrupted by handler */
if (sigaction(SIGFPE, &sa, NULL) == -1)
{
printf("error\n");
}
int mask = feenableexcept(FE_INVALID |
FE_DIVBYZERO |
FE_OVERFLOW |
FE_UNDERFLOW);
printf("mask: %x\n", mask);
volatile double x = 0.0;
volatile double y = 1.0 / x;
printf("y = %f\n", y);
if (cnt == CNT_MAX) {
printf("Exited normally.\n");
}
else {
printf("ERROR!!!!\n");
}
return y;
}
```