简体   繁体   English

线程和系统信号

[英]Thread and system signals

I'm programing a multithreaded program that needs to intercept system signals (such as SIGINT). 我正在编写一个需要拦截系统信号(例如SIGINT)的多线程程序。 I would like to know if there is a normalized way to "catch" these signals like: 我想知道是否存在一种标准化的方式来“捕获”这些信号,例如:

  • A Signal is sent, may any thread receive it or only the main() one ? 发送信号,是任何线程接收它还是仅main()一个?
  • Is there a Posix rule or a programming idiom that specifies how to handle this ? 是否有Posix规则或编程用法来指定处理方式?

It is guaranteed that precisely one thread receives the signal, but it is also unspecified which thread that is. 可以保证只有一个线程接收到该信号,但是也不确定是哪个线程。

The proper thing to do is to block signals on all threads but one, so that that thread alone deals with signal handling; 正确的做法是阻塞除一个线程外的所有线程上的信号,以便该线程单独处理信号处理。 or on Linux specifically block threads everywhere and set up a signalfd to catch signals — that way, you don't introduce any asynchronousity and signals become just one more file descriptor to read from. 或在Linux上专门在任何地方阻塞线程并设置signalfd来捕获信号-这样,您就不会引入任何异步性,并且信号仅会成为一个文件描述符,以供读取。

Since you asked about POSIX, from man signal(7) 由于您是从人信号中询问POSIX的, (7)

POSIX.1 distinguishes the notions of signals that are directed to the process as a whole and signals that are directed to individual threads. POSIX.1区分了针对整个过程的信号和针对各个线程的信号的概念。 According to POSIX.1, a process-directed signal (sent using kill(2), for example) should be handled by a single, arbitrarily selected thread within the process . 根据POSIX.1,进程控制信号(例如,使用kill(2)发送)应由进程内的一个任意选择的线程处理

So in short, it means a random thread will be chosen to handle the signal. 简而言之,这意味着将选择一个随机线程来处理信号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM