1

I trying to make program reload itself after it receives signal. I have this code

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>


void signal_callback_handler(int signum){

   printf("Caught signal %d\n",signum);

   execv("./test", NULL); //reexec myself
}

int main()
{
    signal(SIGINT, signal_callback_handler);


    printf("Program STARTED\n");

        while(1){
        printf("Program processing stuff here.\n");
        sleep(1);
    }
   return EXIT_SUCCESS;
}

The problem is that after exec program just ignore signal instead of calling signal handler. Output:

Program STARTED
Program processing stuff here.
Program processing stuff here.
^CCaught signal 2
Program STARTED
Program processing stuff here.
^C^CProgram processing stuff here. 
^C^C^C^C^CProgram processing stuff here. 
^C^CProgram processing stuff here.

How to make signal handlers work after exec?

user1940679
  • 176
  • 1
  • 11
  • possible duplicate of [Is it possible to signal handler to survive after "exec"?](http://stackoverflow.com/questions/2333637/is-it-possible-to-signal-handler-to-survive-after-exec) – Martin R May 19 '14 at 18:47
  • I have already read this question. And i need opposite thing - i expected that exec will replace process and then signal() will set new signal handler, i don't need to keep old handlers, program will just reinit them, but this reinitialization don't works – user1940679 May 19 '14 at 18:55
  • @MartinR no this is not a duplicate of that. – n. m. could be an AI May 19 '14 at 18:55
  • I have retracted my closing vote ... – Martin R May 19 '14 at 19:00

2 Answers2

3

Signal masks are inherited across exec, and SIGINT is blocked during the invocation of your signal handler, which calls execve. Thus your re-exec'd image is started with SIGINT blocked.

If you strace the process, you'll see that your signal call becomes something like:

3143  rt_sigaction(SIGINT, {0xabcd, [INT], SA_RESTORER|SA_RESTART, 0xabcd}, {SIG_DFL, [], 0}, 8) = 0
                                    ^^^^^
                                      |
                                      +--- SIGINT is blocked during handler!

sigaction will give you finer control over the signal handler, and is recommended over signal.

Community
  • 1
  • 1
pilcrow
  • 56,591
  • 13
  • 94
  • 135
1

Yor signal is blocked during execution of the signal handler, and the signal mask is inherited over exec. You need to reset it explicitly.

A potential problem here is that if you unblock inside the handler, and you have another signal pending, it will be delivered immediately, causing the handler to be executed again. This should be rare but it can happen.

Worse yet, if you unblock in the re-exec'd process and you have a signal pending, you may have it delivered to the re-exec'd process, potentially killing it. So set up a handler in the "child" first, then unblock.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243