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?
catching SIGINT in a multithreaded program
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.
but this way isn't going a sigint signal to be lost if a child-thread happens to catch it and simply ignores it? –
Ipsus
@nikos: Yes, but I don't see the relation to what I was writing; If a thread blocks a signal it can't, per definition, catch it. –
Bissextile
@nikos: A signal is never delivered to a thread that has it blocked (eg. using
pthread_sigmask()
) - this is different to the thread catching and ignoring it. If all threads bar the main thread have SIGINT
blocked, then it will always be delivered to the main thread. –
Shrunken © 2022 - 2024 — McMap. All rights reserved.