Click here to Skip to main content
15,884,099 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
In my application, I try to catch a specific signal which is SIGUSR1, I wrote the below code to do this issue, in which the application will create a thread for "init_signal_catcher".

The problem is when I run the code ,the program goes to sleep forever and does not respond to any signal even if it is SIGUSR1.

So could you please tell me what is the problem in my below code?

C++
static void sig_handler(const int sig_number, siginfo_t *sig_info, void *context)
{
if (sig_number == SIGSEGV)
{
    error_sys("Error at address 0x%lx", (long)sig_info->si_addr);
    exit(-1);
}
sig_value = sig_number;
}


int init_signal_catcher()
{
struct sigaction sig_action; /* Structure describing the action to be taken when asignal arrives.  */

sigset_t oldmask;  /* Signal mask before signal disposition change.      */
sigset_t newmask;  /* Signal mask after signal disposition change.       */
sigset_t zeromask; /* Signal mask to unblock all signal while suspended. */

/* Define signal mask and install signal handlers */
memset(&sig_action, 0, sizeof(struct sigaction));

sig_action.sa_flags = SA_SIGINFO;
sig_action.sa_sigaction = sig_handler;

/* Examine and change a signal action. */
sigaction(SIGHUP, &sig_action, NULL);
sigaction(SIGINT, &sig_action, NULL);
sigaction(SIGTERM, &sig_action, NULL);
sigaction(SIGSEGV, &sig_action, NULL);
sigaction(SIGUSR1, &sig_action, NULL);

    /* Block SIGHUP, SIGINT, SIGTERM, SIGSEGV and SIGUSR1 signals. */
Sigemptyset(&newmask);
Sigaddset(&newmask, SIGHUP);
Sigaddset(&newmask, SIGINT);
Sigaddset(&newmask, SIGTERM);
Sigaddset(&newmask, SIGSEGV);
Sigaddset(&newmask, SIGUSR1);

/* Examine and change blocked signals. */
Sigprocmask(SIG_BLOCK, &newmask, &oldmask);

/* Initialize the empty signal set. */
Sigemptyset(&zeromask);
sig_value = 0;

while ((sig_value != SIGINT) && (sig_value != SIGTERM))
{
    sig_value = 0;

    /*
     * Go to sleep (unblocking all signals) until a signal is catched.
     * On return from sleep, the signals SIGHUP, SIGINT, SIGTERM and
         * SIGUSR1 are again blocked.
     */
        printf("Suspending on %lu mask.", zeromask);

        // Wait for a signal.
    sigsuspend(&zeromask);

    switch(sig_value)
    {
                printf("Caught Signal %d", sig_value);
        case SIGUSR1:
                    printf("Caught SIGUSR1");
                    break;
    }
}

return 0;
}
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900