Using Signals to Handle Exceptions

Signals provide an alternative method (to checking return values) of handling exceptions or failures. The following example code demonstrates how you can check the return value for a failure and also how you can register a handler for handling the failure asynchronously:

#include <signal.h>
#include <stdio.h>
int func()
    int success = 1;
    // function logic
    // success == 1  - Indicates that the function logic succeeded
    // success == 0  - Indicates that the function logic failed
        return 0;
        return -1;
void sighandler(int signum)
    if(signum == SIGUSR1)
        // 'signal' method for checking failure
        printf(“Error: An error occured in func().”);
        printf(“Error: Unknown signal”);
int main(void)
    int retval = 0;
    // When SIGUSR1 arrives, invoke sighandler()
    retval = func();
    if(retval == -1)
        // The return value method used for checking failure
        printf("Error: An error occured in func().");  

Related concepts