sigset_t unix using sigprocmask()

2.3k Views Asked by At

I am trying to print sigset using printf. In this program, I have used sigprocmask to block SIGHUP and SIGTERM. After initializing set and oset to empty sets, they are giving some random hex strings as output. How should I solve this problem??

Also, I have a doubt regarding the expected output of this program if I press Ctrl-C after execution. Does the catcher function also inherit the present signal set and should print the same as set??

#include<stdio.h>
#include<unistd.h>
#include<signal.h>
#include<bits/sigset.h>
void catcher(int sig){
        sigset_t set;
        sigprocmask(SIG_SETMASK, NULL, &set);
        printf("%x inside function\n",set);
}
int main()
{
        sigset_t set,oset;
        signal(SIGINT,catcher);
        sigemptyset(&set);
        sigemptyset(&oset);
        printf("%x\n",oset);
        printf("%x\n",set);
        sigaddset(&set,SIGHUP);
        sigaddset(&set,SIGTERM);
        sigprocmask(SIG_SETMASK,NULL,&oset);
        printf("%x\n",oset);
        printf("%x\n",set); 
        sigprocmask(SIG_BLOCK,&set,&oset);
        pause();
        sigprocmask(SIG_SETMASK,&oset,&set);
        printf("%x\n",set);
}
1

There are 1 best solutions below

2
On

Manual says :

The sigprocmask() function examines and/or changes the current signal mask (those signals that are blocked from delivery). Signals are blocked if they are members of the current signal mask set.

This mask is for the whole process, and is used to block some signals for delivery. There is no inheritence here. There is a mask that describe at each execution point the set of blocked signals.

What you should know is that by default when a signal is catched, it is automatically added to the set of blocked signals (to prevent reentrance to the catching routine), and removed at the end of it.

An execution of your code on my machine gives :

0            // empty set
0            // empty oset
0            // empty oset
4001         // set = { HUP, TERM }
^C4003       // in catcher, signal is automatically blocked set={HUP, INT, TERM}
4001         // after catcher back in old state set={HUP,TERM}

That means that bit 0 and 14 are used for SIGHUP and SIGTERM, and bit 1 for SIGINT, which is exactly what I found in my system header file :

#define SIGHUP  1       /* hangup */
#define SIGINT  2       /* interrupt */
#define SIGTERM 15      /* software termination signal from kill */