user11157060
user11157060

Reputation:

How to fix Signal Handler assignment

For Linux C programming, I have this handler and main method:

void handler(int number, signinfo_t, void *ignore){
    printf("Signaling %d\n", si->si_pid);
}

int main(){
    struct sigaction sig;
    sig.sa_flags = SA_SIGINFO;
    sigemptyset(&sig.sa_mask);
    sig.sa_handler = handler // This line has error 

If I make the handler with just 1 parameter void handler(int num) it works fine; however, I will not be able to use si->si_pid. The warning I am getting is :

 warning: assignment to __sighandler_t from an incompatible pointer type
 -Wincompatible-pointer-types
 sig.sa_handler = handler;

Do I make it sig.sa_action instead? I want to fix the warning

Upvotes: 0

Views: 1796

Answers (1)

Barmar
Barmar

Reputation: 780974

You're assigning the handler function to the wrong member of sig. The declaration of struct sigaction is:

struct sigaction {
    void     (*sa_handler)(int);
    void     (*sa_sigaction)(int, siginfo_t *, void *);
    sigset_t   sa_mask;
    int        sa_flags;
    void     (*sa_restorer)(void);
};

sig.sa_handler is a function with only one argument, the signal number. When you use the SA_SIGINFO flag, you need to assign the 3-argument function to sig.sa_sigaction instead.

int main(){
    struct sigaction sig;
    sig.sa_flags = SA_SIGINFO;
    sigemptyset(&sig.sa_mask);
    sig.sa_sigaction = handler;

Upvotes: 2

Related Questions