Jason
Jason

Reputation: 11363

Signal handler question

We've been covering signals in C/Unix, and the professor gave an example in class that is confusing me. In the main method below, the signal function is called with the included arguments.

main()
{
  signal(SIGALRM, handler);   // install handler

handler is a function defined as static void handler(int param){

According to the Ubuntu man 7 signal, SIGALRM is an integer value 14, and handler is a programmer defined function. However, the integer parameter is not explicitly defined in the signal call, so how does the handler recieve the argument?

EDIT

Thanks for the help. The real problem that tripped me up was that the class hasn't covered typedefs so I didn't know how it was incorporated into the function, and that was the piece that was missing.

Upvotes: 3

Views: 2903

Answers (5)

Eric Anderson
Eric Anderson

Reputation: 1966

I'm not sure if the previous comments answered your question or not. I'm guessing you're asking how the parameter gets to the signal handler. If so:

Every signal handler must have the same signature. It's hard-coded into the kernel that signal handlers will take a single int parameter and have no return value. You don't tell the kernel -- via signal() -- how to call the handler, because you have no choice in the matter. When the kernel decides to call your signal handler, it already knows what signal it wants to send. So it looks up the address of the handler, and then calls that function like

(*pointer_to_handler) (signal_number);

as Paul's answer says.

Upvotes: 3

Paul Beckingham
Paul Beckingham

Reputation: 14895

The handler will be called something like this:

     (*pointer_to_handler) (param);

The 'handler' you pass to signal is just a function pointer, not a call. It is called later.

Upvotes: 1

NPE
NPE

Reputation: 500157

The argument in question (param in your code) is the signal number (SIGALRM). It's not an additional parameter.

Upvotes: 0

Benoit Thiery
Benoit Thiery

Reputation: 6387

You can use the same handler function for several signals, so the handler is passed the signal value (e.g. SIGALRM = 14 in your case).

About the handler parameter, it is explicitely defined in the signature of signal:

typedef void (*sighandler_t)(int);

sighandler_t signal(int signum, sighandler_t handler);

Upvotes: 2

unwind
unwind

Reputation: 399703

The argument is declared in the declaration of the signal() function.

See the manual page, it quotes the declarations from <signal.h>:

typedef void (*sighandler_t)(int);

sighandler_t signal(int signum, sighandler_t handler); 

Upvotes: 1

Related Questions