9

So can someone explain what this is supposed to do:

void (*signal(int sig, void (*func)(int)) ) (int);

It is a definition taken from the standard signal library.

Tony The Lion
  • 61,704
  • 67
  • 242
  • 415

4 Answers4

9

Start with the name:

signal

Go right as far as you can:

signal(int sig, void (*func)(int))

You have a parenthesized list of parameters, so it's a function taking 2 parameters: an int named sig and a function pointer named func (you can analyze it in the same way later).

Then you hit another rightparen, so you go left:

*signal(int sig, void (*func)(int))

So the function signal returns a pointer to... something. Let's take down the parenthesis and go right again, since we can:

(*signal(int sig, void (*func)(int)) ) (int)

We have again a parenthesized list of arguments, so signal returns a pointer to function which takes an int as an only argument. Then go left again:

void (*signal(int sig, void (*func)(int)) ) (int)

Thus the function signal returns the pointer to function taking int and returning void.

Yes, this language is weird, but at least it's consistent. :)

Kos
  • 70,399
  • 25
  • 169
  • 233
7

The function signal takes as arguments:

int sig - a signal value
void (*func)(int) - a pointer to a function that takes an int and returns void

and returns:

void (*)(int) - a function that takes an int and returns void

signal registers a function to be called when the signal occurs and returns the previous function handler.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
1

Basically it allows to decide how to handle a specific signal (identified by argument int sig) sent to your program.

The void (*func)(int) is a pointer to the function that will handle the signal (you can provide a custom one or use SIG_DFL SIG_IGN which are default actions to manage it normally or ignore it).

The function signal then returns the pointer to the handler present BEFORE the call of this function or SIG_ERR is an error occurred. This can be used to restore the default handler lately when you've done with custom behaviour.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Jack
  • 131,802
  • 30
  • 241
  • 343
0

The man page makes this declaration easier to understand by introducing a typedef as:

typedef void (*sighandler_t)(int);

sighandler_t signal(int signum, sighandler_t handler);

sighandler_t is defined as a pointer to a function that accepts an int and returns void.

signal is a function that accepts an int (signal number) and a function pointer and returns a function pointer.

codaddict
  • 445,704
  • 82
  • 492
  • 529