Search code examples
c++c++11stacksignals

Use sigaltstack to dynamically alter stack on which the signal handler runs


I am trying to raise 100 signals (SIGUSR1) and have them all run in their own stack, can someone explain how I can go about doing this? With the following code:

std::signal(SIGUSR1, signal_andler);

for (int i = 0; i < 100; ++i) {
    stack_t stack;
    stack.ss_flags = 0;
    stack.ss_size = FIBER_STACK;
    stack.ss_sp = malloc( FIBER_STACK );
    
    sigaltstack( &stack, 0 );
    
    raise( SIGUSR1 );
}

I read other implementations using sigaction somewhere, but again I have no idea what that is. I apologize if I have completely misunderstood how sigaltstack is supposed to work.


Solution

  • In order for a signal to be delivered on the alternate stack, you need to specify the SA_ONSTACK flag when you register the signal handler:

    struct sigaction act;
    act.sa_handler = signal_handler;
    act.sa_mask = 0;
    act.sa_flags = SA_ONSTACK;
    sigaction(SIGUSR1, &act, 0);
    

    Calling signal is equivalent to calling sigaction with 0 for the flags (not what you want).