csignals

What does this code do ? C


I'm trying to figure out what does this code do, and I could use some help.

int sethandler( void (*f)(int), int sigNo) {
    struct sigaction act;
    memset(&act, 0, sizeof(struct sigaction));
    act.sa_handler = f;
    if (-1==sigaction(sigNo, &act, NULL))
        return -1;
    return 0;
}

void sigchld_handler(int sig) {
    pid_t pid;
    for(;;)
    {
        pid=waitpid(0, NULL, WNOHANG);
        if(0==pid) return;
        if(0>=pid) {
            if(ECHILD==errno) return;
                ERR("waitpid:");
        }
    }
}

This is the function call in main:

if(sethandler(sigchld_handler, SIGCHLD)) 
    ERR("Setting parent SIGCHLD Error:");

ERR just prints out the type of error, and on which line it occurred, it's irrelevant to the question.

The following is what i'm confused about: Which function is called first sethandler or sigchld_handler?. What does (*f)(int)mean?. And what does act.sa_handler = fdo?.


Solution

  • The following is what i'm confused about: Which function is called first sethandler or sigchld_handler?

    sethandler is the only function called directly in this code. The call to sigaction in sethandler may cause sigchld_handler to be called later, however.

    What does (*f)(int) mean?

    void (*f)(int) is a pointer variable named f, pointing to a function which takes one int argument and returns void. (In this case, the function being pointed to is sigchld_handler.)

    And what does act.sa_handler = f do?

    It assigns that pointer to act.sa_handler. This is used to register that function as a signal handler.