Arnaud Rochez Arnaud Rochez - 4 years ago 122
C Question

Don't understand signal

Could someone tell me what this line does:

if(signal(SIGUSR1, handler) == (sighandler_t)-1)

It is a line I copied from an exercise, which made it work, but I don't really understand it. Could someone explain this to me? (It is actually the second part I don't understand: what is the value of (sighandler_t)-1?)

Thank you :)

edit: the sighandler_t comes from

typedef void (*sighandler_t)(int);

Answer Source

First of all, it is a bad style and probably non-portable code, (sighandler_t)-1 should be replaced with one of the predefined signal dispositions. On my system they are declared in next way

/* Fake signal functions.  */
#define SIG_ERR ((__sighandler_t) -1)       /* Error return.  */
#define SIG_DFL ((__sighandler_t) 0)        /* Default action.  */
#define SIG_IGN ((__sighandler_t) 1)        /* Ignore signal.  */

Other systems may use another values, so assuming that your uses the same definitions, we get next code:

if(signal(SIGUSR1, handler) == SIG_ERR) {
    /* got problem */
} else {
   /* handler installed */

This code installs function handler as handler for signal SIGUSR1 and checks returned value to ensure that it was done successfully. handler must be declared as void handler(int signo);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download