Search code examples
csignals

Double signal send with command timeout


I am currently working on a project where I need to manage signals. I am currently using this code

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

void gest_sig_int(int signo) {
    write(1, "I receive a signal\n", 19);
}

int     main(void) {
    struct sigaction s;

    s.sa_handler = gest_sig_int;
    s.sa_flags = 0;
    sigemptyset(&s.sa_mask);
    sigaction(SIGINT , &s, NULL);
    while (1);
    return (0);
}

I compile with

gcc test.c -o test

If I execute the code and use CTRL + C the programme display

./test
^CI receive a signal

Which is exactly the result I want !

But when I am trying to do the same thing with the timeout command my programme receive the signal twice

timeout -s INT 2 ./test
I receive a signal
I receive a signal

I don't know if it's come from my programme or the command timeout

Thanks for reading !


Solution

  • But when I am trying to do the same thing with the timeout command my programme receive the signal twice

    I can reproduce your issue with the timeout command included in GNU coreutils 8.25.

    I don't know if it's come from my programme or the command timeout

    I don't see any reason to think it's your program, and I can observe different behavior if I use a different variation on the timeout command:

    > timeout -k 1 -s INT 2 ./test
    I receive a signal
    Killed
    >
    

    The -k 1 instructs timeout to send a SIGKILL to the child if it does not terminate within one second of receiving the first signal. With this, the test program's signal handler (which is registered only for SIGINT) fires only once, no matter how long a delay is specified for the kill timeout.

    The observed behavior of this version of timeout when a -k option is not specified seems to be to send a second signal of the same type if the child does not terminate within a sub-second delay after the first signal. Indeed, I take this to be established by your experiment, though I do not find it documented.