Why is my signal handler not working? - linux

I want to handle the signal SIGTSTP (18) on Linux. This is my code:
void handler(int signum){
printf("Signal %d has tried to stop me.", signum);
}
int main(void){
struct sigaction act;
sigset_t mask;
act.sa_handler = handler;
act.sa_flags = 0;
sigemptyset(&mask);
sigaddset(&mask, SIGTSTP);
sigprocmask(SIG_SETMASK, &mask, NULL);
sigaction(SIGTSTP, &act, NULL);
pause();
}
When I send a signal from another terminal this way:
$ kill -18 PID
the handler() function does not run.
I've tried replacing SIGTSTP with 18 in the call to sigaction(). It does not work.
Any ideas?
Thanks for your time.

You are deliberately blocking delivery of SIGTSTP to your process by doing
sigaddset(&mask, SIGTSTP);
sigprocmask(SIG_SETMASK, &mask, NULL);
sigprocmask with SIG_SETMASK sets a mask to block signals. Remove the call to sigprocmask, and the signal should be delivered.
One other thing to do is to zero act before filling it in:
memset(&act, 0, sizeof(act));

The most likely reason is that you did not set your struct sigaction act to zero. It will be full of random stack values.
Fix it by using struct sigaction act = {}; or memset(&act, 0, sizeof(act))
Double check that I got the memset argument order right. I sometimes get it mixed up.

Related

How can I print a message from a signal handler

I have small project for practice in system calls. The idea is to create a Rock paper scissors game. The controller need to create two child processes and when two processes are created they are supposed to send ready command to the controller (parent process) using SIGUSR1 signal. I have created the two children processes and the signal sent the signal to the controller but the problem message does not print out. what am I wrong?
Here is my code.
#include<stdio.h>
#include<unistd.h> // fork(); for creating processes and pipe()s
#include<signal.h>
#include<sys/signal.h>
#include<stdlib.h>
void handle_sigusr1(int sig){
printf("Sending ready command...\n");
}
int x = 0;
int main(int args, char* argv[]){
int player0, player1;
player0 = fork();
if(player0 != 0){
player1 = fork();
}
if( player0 == 0){
kill(getppid(), SIGUSR1);
sleep(2);
}else if(player1 == 0){
sleep(3);
kill(getppid(), SIGUSR1);
}else{
wait(NULL);
struct sigaction sa = { 0 };
sa.sa_flags = SA_RESTART;
sa.sa_handler = &handle_sigusr1;
sigaction(SIGUSR1, &sa, NULL);
if(signal(SIGUSR1, handle_sigusr1)){
x++;
printf("Controller: Received ready command. Total %d\n", x);
}
}
return 0;
}
In your code, there are 2 major issues to modify.
First of all, move the signal handler above the wait() function, otherwise you are defining how to handle the signal after receiving it
signal(SIGUSR1, handle_sigusr1);
wait();
Then, the parent process is waiting for only 1 child to receive the signal. You should add a loop to wait both the child processes in the parent statement branch

Proper way of handling SIGCHLD, EINT, and accept() in Linux

I have a program that creates a TCP server. When the accept() connects to a client, I fork() it and handle the connection. When that client leaves it calls the waitpid() because of the SIGCHLD, but this causes a EINTR in the accept(). My question is how should this be handled? I've read so many different ways.
Most say to ignore it the EINT and try the accept() again. I've even seen a macro to do just that: TEMP_FAILURE_RETRY(). Some say to set the sigaction flags SA_RESTART and SA_NOCLDSTOP. I've tried that and it introduces other errors (errno = ECHILD). Also, how should the child exit? I've seen both _exit(0) and exit(0).
int main( int argc, char *argv[] )
{
int sockfd, newsockfd, clilen;
struct sockaddr_in cli_addr;
int pid;
f_SigHandler();
sockfd = f_SetupTCPSocket();
clilen = sizeof(cli_addr);
while (1)
{
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
{
if( errno == EINTR ) continue;
else exit(1) ;
}
pid = fork();
if (pid == 0)
{
close(sockfd);
doprocessing();
close(newsockfd);
_exit(0);
}
else
{
close(newsockfd);
}
}
}
The SIGCHLD handling is:
void f_ChildHandler(int signal_number)
{
while (waitpid(-1, NULL, WNOHANG) > 0)
{
}
}
void f_SigHandler(void)
{
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = f_ChildHandler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGCHLD, &sa, NULL);
}
In your case, a plain SA_RESTART and the waitpid() in the handler probably suffices. When exit code is uninteresting, you can pass SA_NOCLDWAIT additionally.
When client exit must be handled in a more complex way, you can catch EINTR in the main program and call waitpid() there. To make it race free, you should use pselect() to block the signal. Alternatively, you can create a signalfd and use it in select/poll with your sockfd.
Child should use _exit() to prevent execution of atexit() handlers (e.g. which write termination entries into a file).

need to know how to interrupt all pthreads

In Linux, I am emulating an embedded system that has one thread that gets messages delivered to the outside world. If some thread detects an insurmountable problem, my goal is to stop all the other threads in their tracks (leaving useful stack traces) and allow only the message delivery thread to continue. So in my emulation environment, I want to "pthread_kill(tid, SIGnal)" each "tid". (I have a list. I'm using SIGTSTP.) Unfortunately, only one thread is getting the signal. "sigprocmask()" is not able to unmask the signal. Here is my current (non-working) handler:
void
wait_until_death(int sig)
{
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, sig);
sigprocmask(SIG_UNBLOCK, &mask, NULL);
for (;;)
pause();
}
I get verification that all the pthread_kill()'s get invoked, but only one thread has the handler in the stack trace. Can this be done?
This minimal example seems to function in the manner you want - all the threads except the main thread end up waiting in wait_until_death():
#include <stdio.h>
#include <pthread.h>
#include <signal.h>
#include <unistd.h>
#define NTHREADS 10
pthread_barrier_t barrier;
void
wait_until_death(int sig)
{
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, sig);
sigprocmask(SIG_UNBLOCK, &mask, NULL);
for (;;)
pause();
}
void *thread_func(void *arg)
{
pthread_barrier_wait(&barrier);
for (;;)
pause();
}
int main(int argc, char *argv[])
{
const int thread_signal = SIGTSTP;
const struct sigaction sa = { .sa_handler = wait_until_death };
int i;
pthread_t thread[NTHREADS];
pthread_barrier_init(&barrier, NULL, NTHREADS + 1);
sigaction(thread_signal, &sa, NULL);
for (i = 0; i < NTHREADS; i++)
pthread_create(&thread[i], NULL, thread_func, NULL);
pthread_barrier_wait(&barrier);
for (i = 0; i < NTHREADS; i++)
pthread_kill(thread[i], thread_signal);
fprintf(stderr, "All threads signalled.\n");
for (;;)
pause();
return 0;
}
Note that unblocking the signal in the wait_until_death() isn't required: the signal mask is per-thread, and the thread that is executing the signal handler isn't going to be signalled again.
Presumably the problem is in how you are installing the signal handler, or setting up thread signal masks.
This is impossible. The problem is that some of the threads you stop may hold locks that the thread you want to continue running requires in order to continue making forward progress. Just abandon this idea entirely. Trust me, this will only cause you great pain.
If you literally must do it, have all the other threads call a conditional yielding point at known safe places where they hold no lock that can prevent any other thread from reaching its next conditional yielding point. But this is very difficult to get right and is very prone to deadlock and I strongly advise not trying it.

Set mask with sigprocmask works only depending where called

I have a strange behavior where manpage and google didn't help out.
In my code I want to block / unblock SIGINT when SIGUSR2 is sent. For this I install the signal handler and prepare the set for mask in a function:
void installSignallHandler(){
sBlock.sa_handler = handleBlock;
sigemptyset(&sBlock.sa_mask);
sigaddset(&sBlock.sa_mask, SIGUSR2);
sBlock.sa_flags = 0;
sigaction(SIGUSR2, &sBlock, NULL);
sigemptyset(&signals_protected);
sigaddset(&signals_protected, SIGINT);
// For some reason sigprocmask only works if it is called here the first time
// sigprocmask(SIG_BLOCK, &signals_protected, NULL);
// sigintBlocked = true;
}
Then if SIGUSR2 is sent this function is called:
void handleBlock(int signal){
if(sigintBlocked){
printf("Unblocking SIGINT ...\n");
sigprocmask(SIG_UNBLOCK, &signals_protected, NULL);
sigintBlocked = false;
}
else{
printf("Blocking SIGINT ...\n");
sigprocmask(SIG_BLOCK, &signals_protected, NULL);
sigintBlocked = true;
}
}
For testing I called it like this:
int main(int argc, char **argv) {
installSignallHandler();
while(1){
printf("processing...\n");
sleep(1);
}
return EXIT_SUCCESS;
}
Now the problem: The way I posted the code, sigprocmask takes no effect. But if I uncomment the two lines above, it works. So my two questions:
Can you explain this behavior?
What can I do to solve it? - I don't want to start with blocked signal.
because it is race-condition. set sigintBlocked in sig_handler and then do validation in main function if it is set then mask the signal.
this link has more information
sigprocmask during signal's execution

How to safely `waitpid()` in a plugin with `SIGCHLD` handler calling `wait()` setup in the main program

I am writing a module for a toolkit which need to execute some sub processes and read their output. However, the main program that uses the toolkit may also spawn some sub processes and set up a signal handler for SIGCHLD which calls wait(NULL) to get rid of zombie processes. As a result, if the subprocess I create exit inside my waitpid(), the child process is handled before the signal handler is called and therefore the wait() in the signal handler will wait for the next process to end (which could take for ever). This behavior is described in the man page of waitpid (See grantee 2) since the linux implementation doesn't seem to allow the wait() family to handle SIGCHLD. I have tried popen() and posix_spawn() and both of them have the same problem. I have also tried to use double fork() so that the direct child exist immediately but I still cannot garentee that waitpid() is called after SIGCHLD is recieved.
My question is, if other part of the program sets up a signal handler which calls wait() (maybe it should rather call waidpid but that is not sth I can control), is there a way to safely execute child processes without overwriting the SIGCHLD handler (since it might do sth useful in some programs) or any zombie processes.
A small program which shows the problem is here (Noted that the main program only exit after the long run child exit, instead of the short one which is what it is directly waiting for with waitpid()):
#include <signal.h>
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
static void
signalHandler(int sig)
{
printf("%s: %d\n", __func__, sig);
int status;
int ret = waitpid(-1, &status, 0);
printf("%s, ret: %d, status: %d\n", __func__, ret, status);
}
int
main()
{
struct sigaction sig_act;
memset(&sig_act, 0, sizeof(sig_act));
sig_act.sa_handler = signalHandler;
sigaction(SIGCHLD, &sig_act, NULL);
if (!fork()) {
sleep(20);
printf("%s: long run child %d exit.\n", __func__, getpid());
_exit(0);
}
pid_t pid = fork();
if (!pid) {
sleep(4);
printf("%s: %d exit.\n", __func__, getpid());
_exit(0);
}
printf("%s: %d -> %d\n", __func__, getpid(), pid);
sleep(1);
printf("%s, start waiting for %d\n", __func__, pid);
int status;
int ret = waitpid(pid, &status, 0);
printf("%s, ret: %d, pid: %d, status: %d\n", __func__, ret, pid, status);
return 0;
}
If the process is single-threaded, you can block the CHLD signal temporarily (using sigprocmask), fork/waitpid, then unblock again.
Do not forget to unblock the signal in the forked child - although POSIX states the signal mask is undefined when a process starts, most existing programs expect it to be completely unset.

Resources