简体   繁体   English

我是否过度设计了每线程信号阻止?

[英]Am I over-engineering per-thread signal blocking?

In my applications, I generally want to intercept SIGINT and SIGTERM signals in order to close down gracefully. 在我的应用程序中,我通常希望拦截SIGINTSIGTERM信号,以便正常关闭。

In order to prevent worker threads from "stealing" signals, I do this in the entrypoint for each: 为了防止工作线程“窃取”信号,我在每个入口点都这样做:

// Block signals in this thread
sigset_t signal_set;
sigaddset(&signal_set, SIGINT);
sigaddset(&signal_set, SIGTERM);
sigaddset(&signal_set, SIGHUP);
sigaddset(&signal_set, SIGPIPE);
pthread_sigmask(SIG_BLOCK, &signal_set, NULL);

If I don't, when I perform Ctrl + C , some of the time (it's unspecified as to which thread will get the signal) my handlers in the base thread won't be invoked — instead, the signal just terminates the process from within the worker thread. 如果不这样做,则当我执行Ctrl + C时 ,有时(不会指定哪个线程将获得信号)我的基线程中的处理程序将不会被调用-而是,该信号只是终止了在工作线程中。 This is obviously not cool. 这显然不酷。

So I have one signal-handling thread and block signals everywhere else. 所以我有一个信号处理线程,并在其他地方阻塞信号。

However, I don't notice anybody else doing this, it's easy enough to forget to do, and it's also not entirely portable. 但是,我没有注意到其他人在这样做,很容易忘记做,而且也不是完全可移植的。 Is there some more simple trick I'm missing? 我还缺少一些更简单的技巧吗?


References: 参考文献:

I find it a perfectly reasonable thing to do. 我觉得这是完全合理的事情。

You could block the signals in main , before any other thread is spawned. 您可以在产生任何其他线程之前阻止main的信号。 The spawned threads will inherit the creator thread signal mask and you can unblock signals only in the signal handling thread (being careful only if that thread spawns other threads as well). 产生的线程将继承创建者线程的信号掩码,并且您只能在信号处理线程中取消阻止信号(仅当该线程也产生其他线程时要小心)。

Or you can leave the signals blocked everywhere and explicitly handle them via sigwait and friends in the signal handling thread. 或者,您可以将信号保留在各处,并通过sigwait和朋友在信号处理线程中显式处理它们。

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

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