在多线程程序中捕获 SIGINT
我正在编写一个多线程程序,我想处理用户可能发出的 Ctrl-C 命令以终止执行。据我所知,不能保证能够取消每个工作线程的主线程会捕获信号。因此,是否有必要对工作线程的代码使用不同的信号处理程序,以便任何人都可以在信号到达时捕获信号,或者是否有另一种方法可以仅在主线程的代码中使用信号处理程序来实现这一点?
I am writing a multithreaded program where I want to handle a possible Ctrl-C command from the user to terminate execution. As far as I know there is no guarantee that the main thread, which is able to cancel every working thread, will catch the signal. Is it, therefore, necessary to have a different signal handler to the code of the working thread so that anyone will catch the signal if it arrives, or is there another way to do that with having a signal handler only in the main thread's code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 pthread_sigmask() 阻止来自调用线程的信号。
而且,由于阻塞的信号会继承到新创建的线程,因此您可以在主线程中阻塞 SIGINT,然后启动其他线程,然后在主线程中取消阻塞(如果这是更好的做法)。
You can block signals from the calling thread with pthread_sigmask().
And, as the blocked signals are inherited to newly created threads, you can block SIGINT in the main thread, then launch your other threads, and then unblock it in the main thread, if that is preferable.