Pass arguments to signal handler in C

痴心易碎 提交于 2019-12-10 23:35:11

问题


How can I pass arguments (e.g. a pointer to a struct) to a signal handler? I'm writing a multithread application, so I cannot use global variables

I associate a timer to each thread. When timer expires I have to update a struct (each thread has a different struct).

How can I do?


回答1:


The way the signal handler is called by the system is fixed -- there's no way to change it and add an additional user pointer. So if you want to get additional data into the signal handler, the only way to do it is with a global variable (which could be thread-local).

However, if you are trying to use timer_create with threads, you are much better off using SIGEV_THREAD rather than SIGEV_SIGNAL. The latter sends the signal to the process rather than the thread, so it might be caught by any thread in the process.




回答2:


POSIX timers allow to specify the details of how your process will be notified of an expiration using the struct sigevent structure documented in sigevent(7).

To pass context info to the siggnal handler for the generated signal, you can set the .sigev_value.sival_ptr member, which your signal handler will then be able to retrieve (you'll need to set the signal handler via the .sa_sigaction member of struct sigaction, while making sure the structure's .sa_flags is ORred with SA_SIGINFO).



来源:https://stackoverflow.com/questions/38553036/pass-arguments-to-signal-handler-in-c

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