Arnaud Rochez
Arnaud Rochez

Reputation: 668

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);

Upvotes: 0

Views: 124

Answers (2)

Arnaud Rochez
Arnaud Rochez

Reputation: 668

(sighandler_t)-1 is the minus one digit, cast it into sighandler_t type. You must check to see if the signal call has failed.

Upvotes: 0

Sergio
Sergio

Reputation: 8209

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);

Upvotes: 3

Related Questions