0
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>

void handler (int sig)
{
   printf ("Got signal %d\n", sig);
}

int main (int argc, char *argv[])
{
  struct sigaction act;

  memset (&act, '\0', sizeof(act));

  // Use the sa_sigaction field because
  // the handler has two additional parameters
  act.sa_handler = &handler;

  if (sigaction(SIGHUP, &act, NULL) < 0) {
     perror ("sigaction");
     return EXIT_FAILURE;
  }

  if (sigaction(SIGTERM, &act, NULL) < 0) {
     perror ("sigaction");
     return EXIT_FAILURE;
  }

  while (1) sleep (10);

  return EXIT_SUCCESS;
} 

I am a bit confused about "&handler" . What does it mean here? I am new to signal and really hope someone can give me a hint on how it works. Any help would be appreciated. Thx

Nina Liu
  • 33
  • 2
  • It is a function pointer, it will be called when the signal specified by your `sigaction` is sent. – Fantastic Mr Fox Nov 07 '17 at 05:18
  • With functions, `&function` and just `function` mean the same thing — a pointer to the function. The `&` is unnecessary. Were I reviewing the code, the `&` would be removed. – Jonathan Leffler Nov 07 '17 at 06:11

2 Answers2

0

Man page of SIGACTION :

The sigaction structure is defined as something like:

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

[...]

   `sa_handler` specifies the action to be associated with signum and may
   be SIG_DFL for the default action, SIG_IGN to ignore this signal, or
   a pointer to a signal handling function.  This function receives the
   signal number as its only argument.

[...]

Here, sa_handler is a pointer to a function and hold the address of handler() function.

msc
  • 33,420
  • 29
  • 119
  • 214
  • Yep. But what does the "int sig" refers to ? If I use a function pointer I can't pass any argument in right ? Thx – Nina Liu Nov 07 '17 at 05:30
0

As mentioned here,

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

The sa_handler is a function pointer that must point to a signal handling function.

sa_handler specifies the action to be associated with signum and may be SIG_DFL for the default action, SIG_IGN to ignore this signal, or a pointer to a signal handling function. This function receives the signal number as its only argument.

Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34