I'm trying to understand the following example code about signals:
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
sig_atomic_t sigusr1_count = 0;
void handler(int signal_number) {
++sigusr1_count;
}
int main() {
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = &handler;
sigaction(SIGUSR1, &sa, NULL );
printf("SIGUSR1 was raised %d times\n", sigusr1_count);
return 0;
}
The output is:
SIGUSR1 was raised 0 times
Why was the signal not raised?
There are a couple of reasons. The first, is that nothing ever sends SIGUSR1 to your process. The other, more important one, is that you don't give any time for anyone to do so. Immediately after registering your signal handler, you print out how many times the signal was received in, most likely, less then a few milliseconds. You need to add something like sleep(10) before printing out the result.
Because there is nothing sending the SIGUSR1 signal to your application? Did you try running kill -USR1 pid to send the signal? Or kill(pid, SIGUSR1) from this or another application?
Where did you send the signal SIGUSR1? You should sens it after sigaction and before printf... Add a loop in your main function.
Related
Consider the simple example below which registers for a signal handler for SIGABRT, then calls abort(). When I run it, the program terminates before printing Done but after async-signal-safe printing in the trapped signal.
This implies that SIGABRT is not a blockable signal. This seems to be supported by this StackOverflow answer. However, I cannot find any corroborating evidence of that behavior in the signal man page, which clearly states that The signals SIGKILL and SIGSTOP cannot be caught, blocked, or ignored but makes no similar mention for SIGABRT.
Can someone please enlighten me on this behavior?
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
static struct sigaction old_sa;
static void my_handler(int signo)
{
const char x[] = "In Handler\n";
write(STDOUT_FILENO, x, strlen(x));
}
int main()
{
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = my_handler;
sigemptyset(&sa.sa_mask);
sigaddset(&sa.sa_mask, SIGABRT);
if (0 != sigaction(SIGABRT, &sa, &old_sa))
{
perror("sigaction");
exit(EXIT_FAILURE);
}
printf("Ready\n");
abort();
printf("Done\n");
exit(0);
}
Compiled with gcc ./try.c && ./a.out generates the following output
Ready
In Handler
Aborted
SIGABRT can be blocked. But the abort() function unblocks the signal before sending the signal.
This is specified in POSIX:
The abort() function shall override blocking or ignoring the SIGABRT signal.
You'll get the expected result if you use
kill(getpid(), SIGABRT);
instead of calling abort()
Your handler caught the signal. Then it returned. C 2018 7.22.4.1 2 says “The abort function causes abnormal program termination to occur, unless the signal SIGABRT is being caught and the signal handler does not return.” So, once your handler returns, the abort routine continues doing its thing, which is to terminate your program.
If instead of abort(); you use raise(SIGABRT); to raise the signal without calling the abort routine, then the signal handler will be called, will print, and will return, after which printf("Done\n"); will be executed.
Disclaimer: Absolute newbie in C, i was mostly using Java before.
In many C beginner tutorials, waitpid is used in process management examples to wait for its child processes to finish (or have a status change using options like WUNTRACED). However, i couldn't find any information about how to continue if no such status change occurs, either by direct user input or programmatic (e.g. timeout). So what is a good way to undo waitpid? Something like SIGCONT for stopped processes, but instead for processes delayed by waitpid.
Alternatively if the idea makes no sense, it would be interesting to know why.
How about if I suggest using alarm()? alarm() delivers SIGALRM after the countdown passes (See alarm() man page for more details). But from the signals man page, SIGALRM default disposition is to terminate the process. So, you need to register a signal handler for handling the SIGALRM. Code follows like this...
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void sigalrm(int signo)
{
return; // Do nothing !
}
int main()
{
struct sigaction act, oldact;
act.sa_handler = sigalrm; // Set the signal handler
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
#ifdef SA_INTERRUPT // If interrupt defined set it to prevent the auto restart of sys-call
act.sa_flags |= SA_INTERRUPT;
#endif
sigaction(SIGALRM, &act, &oldact);
pid_t fk_return = fork();
if (fk_return == 0) { // Child never returns
for( ; ; );
}
unsigned int wait_sec = 5;
alarm(wait_sec); // Request for SIGALRM
time_t start = time(NULL);
waitpid(-1, NULL, 0);
int tmp_errno = errno; // save the errno state, it may be modified in between function calls.
time_t end = time(NULL);
alarm(0); // Clear a pending alarm
sigaction(SIGALRM, &oldact, NULL);
if (tmp_errno == EINTR) {
printf("Child Timeout, waited for %d sec\n", end - start);
kill(fk_return, SIGINT);
exit(1);
}
else if (tmp_errno != 0) // Some other fatal error
exit(1);
/* Proceed further */
return 0;
}
OUTPUT
Child Timeout, waited for 5 sec
Note: You don't need to worry about SIGCHLD because its default disposition is to ignore.
EDIT
For the completeness, it is guaranteed that SIGALRM is not delivered to the child. This is from the man page of alarm()
Alarms created by alarm() are preserved across execve(2) and are not inherited by children created via fork(2).
EDIT 2
I don't know why it didn't strike me at first. A simple approach would be to block SIGCHLD and call sigtimedwait() which supports timeout option. The code goes like this...
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
sigset_t sigmask;
sigemptyset(&sigmask);
sigaddset(&sigmask, SIGCHLD);
sigprocmask(SIG_BLOCK, &sigmask, NULL);
pid_t fk_return = fork();
if (fk_return == 0) { // Child never returns
for( ; ; );
}
if (sigtimedwait(&sigmask, NULL, &((struct timespec){5, 0})) < 0) {
if (errno == EAGAIN) {
printf("Timeout\n");
kill(fk_return, SIGINT);
exit(1);
}
}
waitpid(fk_return, NULL, 0); // Child should have terminated by now.
/* Proceed further */
return 0;
}
OUTPUT
Timeout
The third argument to waitpid takes a set of flags. You want to include the WNOHANG flag, which tells waitpid to return immediately if no child process has exited.
After adding this option, you would sit in a loop a sleep for some period of time and try again if nothing has exited. Repeat until either a child has returned or until your timeout has passed.
Waiting for process to die on a typical Unix system is an absolute PITA. The portable way would be to use various signals to interrupt wait function: SIGALARM for timeout, SIGTERM/SIGINT and others for "user input" event. This relies on a global state and thus might be impossible to do.
The non-portable way would be to use pidfd_open with poll/epoll on Linux, kqueue with a EVFILT_PROC filter on BSDs.
Note that on Linux this allows waiting for a process to terminate, you will still have to retrieve status via waitid with P_PIDFD.
If you still want to mix in "user events", add signalfd to the list of descriptors on Linux or EVFILT_SIGNAL filter of kqueue on BSDs.
Another possible solution is to spawn a "process reaper" thread which is responsible for reaping of all processes and setting some event in a process object of your choice: futex word, eventfd etc. Waiting on such objects can be done with a timeout. This requires everyone to agree to use the same interface for process spawning which might or might not be reasonable. Afaik Java implementations use this strategy.
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 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.
Revisiting this question:
I have multiple threads running (pthreads api), each with it's own timer that calls a function handler(int signum) after a certain interval. As these threads call handler and within the function handler, how do I know which thread called it? Is thread-specific data required?
I notice that the thread that enters the handler function is a different thread from the one that set it up, so calling pthread_self() doesn't work. How do I get around this?
Here is a small example illustrating the problem
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
void handler(int);
void call_alarm();
void *setup(void*);
pthread_t p;
void handler(int signum)
{
printf("handler thread %lu\n", pthread_self());
}
void call_alarm()
{
static struct itimerval timer;
static struct sigaction sa;
printf("call_alarm %lu\n", (unsigned long)pthread_self());
sa.sa_handler = handler;
sa.sa_flags = SA_RESETHAND;
timer.it_value.tv_usec = 500;
timer.it_value.tv_sec = 0;
timer.it_interval.tv_sec = 0;
timer.it_interval.tv_usec = 0;
sigaction(SIGALRM, &sa, 0);
setitimer(ITIMER_REAL, &timer, 0);
}
void *setup(void *param)
{
while(1)
{
printf("caller thread %lu\n", pthread_self());
call_alarm();
pause();
}
}
int main(void)
{
if(pthread_create(&p, NULL, setup, NULL));
while(1);
return 0;
}
Output:
caller thread 3086637968
call_alarm 3086637968
handler thread 3086640832
As you can see it prints out different values.
You can print the thread ID when the handler is called:
On Linux: gettid()
On Windows GetCurrentThreadId().
and if you can't, write a function wrapper around the handler and tell your code to call the wrapper function instead of calling the handler directly.
The POSIX chapter on Signal Generation and Delivery states:
At the time of generation, a determination shall be made whether the signal has been generated for the process or for a specific thread within the process. Signals which are generated by some action attributable to a particular thread, such as a hardware fault, shall be generated for the thread that caused the signal to be generated. Signals that are generated in association with a process ID or process group ID or an asynchronous event, such as terminal activity, shall be generated for the process.
I wonder if the SIGALRM signal you're catching is not considered a action attributable to a particular thread, such as a hardware fault. It sounds like your SIGALRM signal falls into the second category, and is being generated for the process.