I was doing a little reading about sigaction() (sources are from my course notes) and I'm not sure I understand this text:
The signal mask is calculated and installed only for the duration of
the signal handler.
By default, the signal “sig” is also blocked when the signal occurs.
Once an action is installed for a specific signal using sigaction,
it remains installed until another action is explicitly requested.
Does this mean that the default signal mask is restored after returning form the signal handler?
Also, do I have to re-install the handler after using it, as if I was using signal()?
Also, there's this piece of code:
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void termination_handler(int signum) {
exit(7);
}
int main (void) {
struct sigaction new_action,old_action;
new_action.sa_handler = termination_handler;
sigemptyset(&new_action.sa_mask);
sigaddset(&new_action.sa_mask, SIGTERM);
new_action.sa_flags = 0;
sigaction(SIGINT, NULL, &old_action);
if (old_action.sa_handler != SIG_IGN) {
sigaction(SIGINT,&new_action,NULL);
}
sleep(10);
return 0;
}
So - how exactly will SIGTERM be handled? I can see that the installed handler is termination handler(), but then SIGTERM was added to the signal mask with no use of sigprocmask(). What does this mean? Thanks!
P.s. one last question: why the if statement in main()?
Let's try to understand what's happening with a modified version of your code :
#include <signal.h>
#include <stdio.h>
void termination_handler(int signum)
{
printf("Hello from handler\n");
sleep(1);
}
int main (void)
{
//Structs that will describe the old action and the new action
//associated to the SIGINT signal (Ctrl+c from keyboard).
struct sigaction new_action, old_action;
//Set the handler in the new_action struct
new_action.sa_handler = termination_handler;
//Set to empty the sa_mask. It means that no signal is blocked
// while the handler run.
sigemptyset(&new_action.sa_mask);
//Block the SEGTERM signal.
// It means that while the handler run, the SIGTERM signal is ignored
sigaddset(&new_action.sa_mask, SIGTERM);
//Remove any flag from sa_flag. See documentation for flags allowed
new_action.sa_flags = 0;
//Read the old signal associated to SIGINT (keyboard, see signal(7))
sigaction(SIGINT, NULL, &old_action);
//If the old handler wasn't SIG_IGN (it's a handler that just
// "ignore" the signal)
if (old_action.sa_handler != SIG_IGN)
{
//Replace the signal handler of SIGINT with the one described by new_action
sigaction(SIGINT,&new_action,NULL);
}
while(1)
{
printf("In the loop\n");
sleep(100);
}
return 0;
}
So, if you compile it and launch it, and press Ctrl+C, then you'll have the handler message executed, and then you get back immediately out of the main's sleep. You can do it as many time as you want, and the handler message and the inloop message are still displayed.
So, you give a function, and sigaction does everything needed to hook the signal with your handler.
Now, what about sigterm? If you increase the sleep time in termination_handler, you can type something like "pkill --signal SIGTERM ./a.out" after pressing Ctrl+C. Then, what happens? Nothing! The SIGTERM signal is blocked while termination_handler is running. But once you are back in the main, now the SIGTERM will kill the application.
(Remember, while you are testing this code, you can still kill applications by sending a SIGKILL signal.)
If you want to know more, and have more fun with signals, you have the signal manual and the sigaction manual which tell a lot more. Notice that you also have the detailed description of the sigaction structure.
Related
Setting a signal handler as SIG_IGN ignores the signal while running the program normally but not while running it through gdb.
I'm creating a timer using timer_create and timer_settime functions. I don't want to use a signal handler (i.e a function) to handle the signals generated by this timer. I decided to use sigwait and wait for SIGALRM. I set the handler for SIGALRM as SIG_IGN and used sigwait.
#include <stdio.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
#define TRUE 1
#define ISTRUE(x) (x != 0)
#define bool int
int main() {
struct itimerspec timer_spec;
struct sigevent sig_event;
timer_t timer_id;
sigset_t sig_set;
timer_spec.it_interval.tv_sec = 1;
timer_spec.it_interval.tv_nsec = 0;
timer_spec.it_value.tv_sec = 1;
timer_spec.it_value.tv_nsec = 0;
sig_event.sigev_signo = SIGALRM;
sig_event.sigev_notify = SIGEV_SIGNAL;
signal(SIGINT, SIG_IGN);
signal(SIGALRM, SIG_IGN);
/* Create the timer */
timer_create(CLOCK_REALTIME, &sig_event, &timer_id);
timer_settime(timer_id, 0, &timer_spec, NULL);
sigemptyset(&sig_set);
sigaddset(&sig_set, SIGALRM);
int signal = 0;
bool running = TRUE;
while (ISTRUE(running)) {
sigwait(&sig_set, &signal);
switch(signal){
case SIGINT:
printf("Interrupt received.. exiting\n");
running = 0;
break;
case SIGALRM:
printf("Ticked\n");
break;
}
printf("Sleeping\n");
}
return 0;
}
While debugging the application in my IDE (CLion) as well as using gdb from the shell, the program functioned as expected. SIGALRM was not being ignored, which led me to believe that what I was doing was right. However, running the application normally, sigwait never returns.
I later realized that this was because the signal was being ignored and I needed to block the signal (using sigprocmask or similar) and set it to a pending state.
Why does, while debugging, the signal get passed through? Is this supposed to happen? What am I missing?
You should look into the handle gdb command:
(gdb) handle SIGALRM
Signal Stop Print Pass to program Description
SIGALRM No No Yes Alarm clock
(gdb) handle SIGALRM ignore
Signal Stop Print Pass to program Description
SIGALRM No No No Alarm clock
(gdb) help handle
... read it ;-) ...
As mentioned in the manpage of ptrace(2) (which gdb is using):
While being traced, the tracee will stop each time a signal is delivered, even if the signal is being ignored.
I'm supposed to write a C program which handles the first SIGINT with a custom handler, and then reset the default behaviour. My custom SIGINT handler should just print a msg. This is what I wrote:
#include <string.h>
#include <strdio.h>
#include <errno.h>
#include <stdlib.h>
#include <signal.h>
void handler(sig)
int sig;
{
printf("%d received\n",sig);
}
int main(){
signal(SIGINT, handler);
signal(SIGINT, SIG_DFL);
while(1);
exit(0);
}
If I launch it from a shell and then I enter Ctrl+C on the same tab, it works. If I try to send the SIGINT using kill -INT *process pid* it just terminates the program, no msg printed. Any idea why?
The signal function is not cumulative. You call it twice, so the last one is the good one, using the default behavior (SIG_DFL).
You have to just set your handler in main and in handler to set the new behavior (signal(SIGINT, SIG_DFL);) so that next signal will be default-treated (kill the process).
Note that signal may have different behavior on different unix systems, so you should have a look to sigaction which is the recommanded way to handle signals.
Possibly ecause signal(SIGINT, SIG_DFL); turns the handler off with respect to the kill. The man page has more info about if or when you need that line, and suggests using sigaction instead of signal for consistent behaviour across platforms:
struct sigaction sa;
sa.sa_handler = handler;
sigaction(SIGINT, &sa, NULL);
I am playing with the signal.h and unistd.h libraries, and I am having some issues. In the code below, when I send the SIGINT signal to my running program by calling CTRL-C, the signal is caught. However, when pressing CTRL-C again, the program terminates. As I understand it, the print statement "Received signal 2" should be printed every time I press CTRL-C.
Is my understanding of this signal incorrect, or is there a bug in my code?
Thanks for your input!
#include "handle_signals.h"
void sig_handler(int signum)
{
printf("\nReceived signal %d\n", signum);
}
int main()
{
signal(SIGINT, sig_handler);
while(1)
{
sleep(1);
}
return 0;
}
Terminal output:
xxx#ubuntu:~/Dropbox/xxx/handle_signals$ ./handle_signals
^C
Received signal 2
^C
xxx#ubuntu:~/Dropbox/xxx/handle_signals$
Edit: Here is the header I've included
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
void sig_handler(int signum);
Thanks for your responses. Reading through them now!
Don't use signal, use sigaction:
The behavior of signal() varies across UNIX versions, and has also varied historically across different versions of Linux. Avoid its use: use sigaction(2) instead.
http://man7.org/linux/man-pages/man2/signal.2.html
In the original UNIX systems, when a handler that was established using signal() was invoked by the delivery of a signal, the disposition of the signal would be reset to SIG_DFL, and the system did not block delivery of further instances of the signal.
Linux implements the same semantics: the handler is reset when the signal is delivered.
The behaviour of signal upon receiving the first signal varies on different implementation. Typically, it requires reinstalling the handler after receiving the signal as handler is reset to its default action:
void sig_handler(int signum)
{
signal(SIGINT, sig_handler);
printf("\nReceived signal %d\n", signum);
}
which is one of the reasons you shouldn't use signal anymore and use sigaction. You can see a bare bone example of using sigaction here.
I'm trying to create a program that blocks the signal SIGUSR1 and the it unblocks the signal.
In the middle I want to see that the signal is blocked using sigpending. But it always says that the signal isn't blocked, and I can use the signal when it's supposed to be blocked.
This is the code that I have.
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
static void signals(int signaln)
{
switch (signaln) {
case SIGUSR1:
printf("Signal SIGUSR1\n"); break;
}
return;
}
main()
{
sigset_t set,set2;
struct sigaction sigs;
sigs.sa_handler = signals;
sigemptyset(&sigs.sa_mask);
sigs.sa_flags=SA_ONESHOT;
sigaction(SIGUSR1, &sigs,0);
sigemptyset(&set);
sigemptyset(&set2);
sigaddset(&set,SIGUSR1);
if(sigprocmask(SIG_BLOCK, &set, NULL)==0){
printf("Blocking SISGUSR1...\n");
}
sigpending(&set2);
if (sigismember(&set2,SIGUSR1)==1)
{
printf("The signal is blocked\n"); //it should print this
}
wait(2);
kill(getpid(),SIGUSR1); //the signal shouldn't work
wait(2);
if(sigprocmask(SIG_UNBLOCK, &set, NULL)==0){
printf("Unblocking SIGUSR1\n");
}
}
Could anyone help me?
sigpending doesn't tell you whether a signal is blocked. It tells you whether a signal is waiting to be delivered. (i.e., the signal is blocked and one has been sent.)
Also, blocked doesn't meean that the signal won't be delivered; it means that the signal won't be delivered now. So you can send the signal, and it will be delivered as soon as the signal is unblocked; probably after the call to sigprocmask(SIGUNBLOCKED...) but before the call to printf, so you'll probably see the signal received message before you see the "unblocking" message.
I have a main application that spawns a seperate thread to process messages off a queue. I have an issue on AIX when I hit CTRL-C as it seems to make some "connection handles" in the thread become invalid. I do have a shutdown hook in the main program catching the SIGINT but on AIX it seems to somehow send a signal to the thread as well...although that is not really possible from what I hear...
Essentially I would like to know if I want the MAIN application to handle ALL signals I am interested in and have the thread/s NEVER handle any signals...is that "good practice"?
If so how can I NOT use "sigwait" in the thread...in fact I do not want any "signal code" in the thread/s...they must simply not receive any signals at all.
I have emptied out all the signals:
sigemptyset(&set);
And have set the SIG_BLOCK
s = pthread_sigmask(SIG_BLOCK, &set, NULL);
So here is a dummy test programe:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#define handle_error_en(en, msg) do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
static void * threadMainLoop(){
//Here I do not want the thread to use "sigwait"....
while(running == TRUE){
//do some thread work and never have any signals come in
}
}
void shutdownHook(int sig){
printf("\nCtrl-C pressed....shutdown hook in main...\n");
}
void signalErrorHandler(int signum){
printf("\nSignal error handler in main...\n");
}
int main(int argc, char *argv[]){
pthread_t thread;
sigset_t set;
int s;
//Catch the following signals in the MAIN thread
(void) signal(SIGINT, shutdownHook);
(void) signal(SIGSEGV, signalErrorHandler);
(void) signal(SIGBUS, signalErrorHandler);
(void) signal(SIGILL, signalErrorHandler);
(void) signal(SIGTERM, signalErrorHandler);
(void) signal(SIGABRT, signalErrorHandler);
sigemptyset(&set); //BLOCK all signals
s = pthread_sigmask(SIG_BLOCK, &set, NULL);
if (s != 0)
handle_error_en(s, "pthread_sigmask");
s = pthread_create(&thread, NULL, &threadMainLoop, (void *) NULL);
if (s != 0)
handle_error_en(s, "pthread_create");
pause();
}
If I just create a thread and have, for example, the SIGINT signal handler in the MAIN thread but do NOT has the SIG_BLOCK set for the thread and the user hits CTRL-C....does the thread get affected at all even though the signal handler in the main thread runs? That seems to be what I am seeing on AIX ;-(
Thanks for the help, much appreciated
Lynton
With s = pthread_sigmask(SIG_BLOCK, &set, NULL); , you're not blocking anything.
Use:
sigfillset(&set);
sets = pthread_sigmask(SIG_SETMASK, &set, NULL);
If you want to block every signal, or explicitly add the signals you want to block to the set if you're using SIG_BLOCK.
After you've created the threads, you need to restore the signal mask, otherwise no threads will catch any signal.
However, looking at your previous question, it might be that the thread catching the signal doesn't handle being interrupted. That is, if you're blocked doing a syscall, and a signal arrives, that syscall gets aborted. Some operating systems defaults to automatically call the system call again, some returns an error and sets errno to EINTR, which the application must handle - and bad things might happen if that's not handled.
Instead, install your signal handlers with sigaction() instead of signal() , and set the SA_RESTART flag, which will cause system calls to automatically restart in case it got aborted by a signal.
Still wrong design.
Do not use CTRL+C to stop an application in a controlled manner.
Use a correctly designed controller app that will be accessible over CORBA, RMI, or some other method to interact with the user and control the background app.
Have fun guys...