线程和进程的不同信号处理程序?是否可以 [英] different signal handler for thread and process?. Is it possible

查看:57
本文介绍了线程和进程的不同信号处理程序?是否可以的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于信令的问题很少.

1)当进程与主线程一起具有更多线程时,并且如果引发了信号,则哪个线程将停止其处理并继续进行信号处理程序?是主线程还是主线程以外的线程?

2)是否可以为主线程和特定线程之间的同一信号保留不同的处理程序?

解决方案

信号可以发送到进程或特定线程.对于发送到进程的信号,只要有至少一个线程未阻塞该信号,便会立即发送该信号;如果有多个这样的线程,则可能会将该信号传递给其中的任何一个(不可预知的是,一).对于发送到特定线程的信号,只要该线程没有信号被阻止,它们就会立即传递.

使用 raise 函数引发信号会将信号发送到名为 raise 的线程,而不是整个过程.由于线程所做的事情而自动生成的信号(例如 SIGSEGV SIGFPE SIGPIPE )也将传递到该特定线程.

从终端生成的信号( SIGINT SIGTSTP SIGQUIT )将传递到整个过程.

无法为每个线程安装单独的信号处理程序,但是信号的信号处理程序可以检查其运行在哪个线程中.如果您知道信号没有中断async-signal-unsafe函数,您可以调用 pthread_self 来获取当前线程ID.否则,一种丑陋但安全的方法是获取 errno 的地址,并基于该地址查找您所在的线程(您必须自己保留一个映射表,并确保对它的访问表是异步信号安全的).

Have few questions regarding Signaling.

1) when the process has few more threads along with main thread, and if the signal is raised, which thread will stop its processing and continue with signal handler ? Is it main thread or other than main thread ?

2) Is it possible to keep different handler for the same signal between main thread and specific thread ?

解决方案

Signals can be sent to either a process or a particular thread. For signals sent to the process, the signal will be delivered as soon as there is at least one thread where that signal isn't blocked, and if there's more than one such thread, it may be delivered to any one of them (unpredictable which one). For signals sent to a particular thread, they're delivered as soon as that thread does not have the signal blocked.

Using the raise function to raise a signal sends the signal to the thread that called raise, not the whole process. Signals automatically generated as a result of things the thread does (like SIGSEGV SIGFPE, and SIGPIPE) are also delivered to that particular thread.

Signals generated from the terminal (SIGINT, SIGTSTP, SIGQUIT) are delivered to the whole process.

There is no way to install separate signal handlers for each thread, but the signal handler for a signal may be able to examine which thread it's running in. If you know the signal did not interrupt an async-signal-unsafe function, you could call pthread_self to get the current thread id. Otherwise, one ugly but safe method is to take the address of errno and look up which thread you're in based on that (you'll have to keep a mapping table yourself and ensure that access to this table is async-signal-safe).

这篇关于线程和进程的不同信号处理程序?是否可以的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆