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.
The argument in question (
param
in your code) is the signal number (SIGALRM
). It's not an additional parameter.The argument is declared in the declaration of the
signal()
function.See the manual page, it quotes the declarations from
<signal.h>
: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
: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 likeas Paul's answer says.
The handler will be called something like this:
The 'handler' you pass to signal is just a function pointer, not a call. It is called later.