0

I am trying to explore Signals in C Language. I was expecting the bellow code should print Error Signal in the console. but it doesn't. I am using Visual Studio 2017 C++ console application.

Do I need to set any setting here?

#include <stdio.h>
#include <signal.h>

static void catch_function(int signo)
{
    printf("Error Signal");
}


int main()
{
    int i = signal(SIGFPE, catch_function);

    int x = 0;
    int y = 100;
    int z = y / x;
    printf("Hello World %d", &z);
    return 0;
}
Student
  • 805
  • 1
  • 8
  • 11
Gopinath
  • 55
  • 1
  • 5
  • 1
    1.) handling of signals is OS dependent. Windows doesn't ever deliver SIGFPE for code that doesn't have any floating-point operations. 2.) A division by an **integer** zero is **undefined behavior** in any case. Your compiler could be smart enough to just drop this invalid code. –  Jul 21 '18 at 08:38

1 Answers1

1

As mentioned by @Felix Palmen, man page says divide be zero results in undefined, it is not guaranteed that all the platforms/architectures support SIGFPE signal Directly quote from the man page

Integer division by zero has undefined result. On some architectures it will generate a SIGFPE signal.

So it is not guaranteed all the platforms support SIGFPE, In your case it is Visual Studio causing the issue, I did try following code in eclipse with gcc in cygwin it worked flawlessly.

#include <stdlib.h>
#include <signal.h>
#include <stdio.h>

void SignalHandler(int signal)
{
 if(signal == SIGFPE) {
        printf("sigfpe received\n");
    }
}

int main()
{
    signal(SIGFPE, SignalHandler);

    int x = 0;
    int y = 100;
    int z = y / x;

    printf("Hello World %d", z);
    return 0;
}
yadhu
  • 1,253
  • 14
  • 25
  • Which is because cygwin mimics POSIX in windows, therefore delivers a SIGFPE to a process if **any** arithmetic error occurs. Still the behavior depends on the compiler, it could just as well optimize away the undefined behavior completely :) –  Jul 21 '18 at 09:38