Search code examples
csignalssignal-handling

How to Raise/Handle Custom Signals in C?


I am trying raise and handle custom signals in C. Unfortunately, I am having only partial success.

I am trying to follow this example: https://www.techonthenet.com/c_language/standard_library_functions/signal_h/raise.php

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

sig_atomic_t signaled = 0;

#define TEST_SIGNAL_50 50
#define TEST_SIGNAL_51 51
#define TEST_SIGNAL_52 52
#define SIGUSR1 50

void sigHandler(int sig)
{
    signaled = 1;

    //Switch statement to handle all signals
    switch(sig) {
        case TEST_SIGNAL_50:
            printf("Case 50 is Matched.\n");
            break;
        case TEST_SIGNAL_51:
            printf("Case 51 is Matched.\n");
            break;
        case TEST_SIGNAL_52:
            printf("Case 52 is Matched.\n");
            break;
        case SIGINT:
            printf("SIGINT Case is Matched.\n");
            break;
        default:    //Raised signal is not a match
            printf("Raised signal %d is not a match.\n", sig);
            break;

    }
}

int main() {
    printf("Hello, World! Test\n");
    
    int raiseResult;
    void (*prev_handler)(int);

    //Register the signal handler
    //prev_handler = signal(SIGINT, sigHandler);     //This works
    //prev_handler = signal(TEST_SIGNAL_50, sigHandler);
    prev_handler = signal(SIGUSR1, sigHandler);

    /* ... */
    //raiseResult = raise(SIGINT);                  //This works
    raiseResult = raise(SIGUSR1);
    /* ... */

    printf("raiseResult =%d.\n",raiseResult );
  
    printf("signaled =%d.\n",signaled);
  
    return 0;
}

The ultimate goal is to be able to handle the different signals by doing various actions. But for the moment, simply hitting the switch statement and getting the corresponding message would be a win.

I know that SIGINT is an actual signal. Thus, sigHandler() will work when I raise SIGINT. But otherwise, I am out of luck. The return value I get from signal() is negative; which tells me my failure has to do with signal().

Does anyone understand what I am doing incorrectly with signal()?


Solution

  • As some users were indicating, Windows and the C compiler on Windows that I was using were not handling signals as cleanly as on a Linux system. Taking my code over to a Linux based system (in my case Ubuntu) and it would perform as expected.