Signal handler question

牧云@^-^@ 提交于 2019-12-10 21:43:47

问题


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.


回答1:


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.




回答2:


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);



回答3:


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:


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.




回答5:


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



来源:https://stackoverflow.com/questions/5473645/signal-handler-question

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!