I have console C++ application built in XCode 6 and want to add SIGTERM handler to it. There are a lot of examples, but I can't get them to work.
#include <csignal>
namespace
{
volatile std::sig_atomic_t gDone = 0;
}
static void term_handler(int i)
{
gDone = 1;
}
int main(int argc, const char * argv[])
{
std::signal(SIGTERM, term_handler);
while (!gDone);
return 0;
}
The debugger stopped on the while
statement, but the handler was not called. The same problem with this code
#include <signal.h>
volatile sig_atomic_t gDone = 0;
void term_handler(int i)
{
gDone = 1;
}
int main(int argc, char* argv[])
{
struct sigaction sa;
sigset_t newset;
sigemptyset(&newset);
sigaddset(&newset, SIGHUP);
sigprocmask(SIG_BLOCK, &newset, 0);
sa.sa_handler = term_handler;
sigaction(SIGTERM, &sa, 0);
while(!gDone);
return 0;
}
Is there a problem with the code? What is the right way to handle signals in OSX?
After you send the signal, and the debugger stops, you have to continue to get to your breakpoint inside the signal handler.
Your code is fine. Kill with:
because
where 31573 was my process ID, did not exit gracefully. I added a printf to your code to tell me it was exiting gracefully.
OK, I'm home now and working on my Mac. Again, your code (second sample specifically) has proven just fine. The confirmation was done in Terminal with gcc and "kill -TERM ". Source refers to SIGTERM, like normal, but kill refers (on OS X) to TERM. The XCode pause you are seeing is due to XCode, not your code. I tried it both ways, Terminal and XCode. I could not find a pref to inhibit that interruption, however.
Just to focus here ...You asked, Is there a problem with the code? Answer: No. You asked, What is the right way to handle signals in OSX? Answer: The way you're already doing it. New question: How do I get XCode (lldb) to not pause when signals occur? Answer: How to tell LLDB debugger not to handle SIGBUS?