Signal handler question

2019-07-05 03:43发布

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.

标签: c linux signals
5条回答
聊天终结者
2楼-- · 2019-07-05 03:46

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

查看更多
别忘想泡老子
3楼-- · 2019-07-05 03:52

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); 
查看更多
做自己的国王
4楼-- · 2019-07-05 03:57

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);
查看更多
beautiful°
5楼-- · 2019-07-05 04:11

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.

查看更多
该账号已被封号
6楼-- · 2019-07-05 04:11

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.

查看更多
登录 后发表回答