0

The following code should print out "Received SIGFPE, Divide by Zero Exception" and then exit, but when I run it in Xcode it stops, opens the debugger, and says "Thread 1: EXC_ARITHMETIC (code=EXC_I386_DIV, subcode=0x0)". When I run the program from the terminal, it works exactly as intended, but I'd much prefer to write my code in the Xcode IDE.

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

void handler_dividebyzero(int signum);

int main(int argc, const char * argv[]) {
    int result = 0;
    int v1 = 0, v2= 0;
    void (*sigHandlerReturn) (int);
    
    sigHandlerReturn = signal(SIGFPE, handler_dividebyzero);
    
    if (sigHandlerReturn == SIG_ERR) {
        perror("Signal Error: ");
        return 1;
    }
    
    v1 = 121;
    v2 = 0;
    result = v1 / v2;
    printf("Result of Divde by Zero is %d\n", result);
    return 0;
}

void handler_dividebyzero(int signum) {
    if (signum == SIGFPE) {
        printf("Received SIGFPE, Divide by Zero Exception\n");
        exit(0);
    }
    else {
        printf("Received %d signal\n", signum);
        return;
    }
}
LN2815
  • 1
  • This could be a debugger feature where it's automatically trapping signals like this, but you can always continue in the debugger. – tadman Nov 17 '20 at 18:23
  • Note, if you're dividing by zero a lot your code is just plain buggy and no amount of signal handling can fix that. – tadman Nov 17 '20 at 18:24
  • Yeah I think it's a debugger feature, but I'm new to MacOS, Xcode, and LLDB so I'm not really sure how to turn it off. And the div by zero is intentional. I'm learning about signal handling so I want the computer to freak out so I can handle it. Works fine when run from the terminal. But coding in vim is a pain compared to the IDE – LN2815 Nov 17 '20 at 18:30
  • @LN2815 Running code in terminal does not imply writing it in `vim`.. .you can code and compile in IDE and run in terminal. – Eugene Sh. Nov 17 '20 at 18:34
  • You can always compile in XCode and run in the terminal. Does [this answer](https://stackoverflow.com/questions/16989988/disable-signals-at-lldb-initialization) add any insight? – tadman Nov 17 '20 at 18:35
  • The accepted answer on the linked question looks good: https://stackoverflow.com/questions/42522683/how-to-tell-lldb-to-pass-signal-onto-program – Phillip Mills Nov 17 '20 at 21:22

0 Answers0