2

Having this in c:

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

void handler(int num){
    write(1, "I won't die!\n", 13);
}

int main(){
    signal(SIGINT, handler);
    while(1){
        printf("wastings cycles. %i\n",getpid());
        sleep(1);
    }
}

If compiled with gcc, then for the first time the ^C is pressed, the handler gets activated and thus print

wastings cycles. 19361
^CI won't die!

but for the second time the C^ is pressed, it will die:

wastings cycles. 19361
^C
Command terminated

Tha is for gcc. However for compiled with clang:

wastings cycles. 22247
^CI won't die!
wastings cycles. 22247
^CI won't die!
wastings cycles. 22247
^CI won't die!
wastings cycles. 22247
^CI won't die!
wastings cycles. 22247
^CI won't die!
wastings cycles. 22247
^CI won't die!
wastings cycles. 22247
^CI won't die!

It never dies. Why? It is the same source, the same hader signal.h, but other compiler uses different output. Gcc != clang. Can someone explain me why the difference?

milanHrabos
  • 2,010
  • 3
  • 11
  • 45
  • under rapbian raspberrypi 4.19.118 on PI4 using gcc 8.3.0 Cntrl-C does not kill the program whatever the number of times I press it – bruno Jun 22 '20 at 18:02
  • I used x64 debian 10 – milanHrabos Jun 22 '20 at 18:31
  • 1
    Please see [this answer](https://stackoverflow.com/a/60784345/1566221) which shows GCC producing both behaviours, depending on whether it's told to use C11 or not. Posix (and I) recommend that you **do not** instill signal handers with `signal`; use `sigaction` instead and think about the flags you use. (And let me know if your question is answered by that other answer, so that we can mark this one as a duplicate. Thanks.) – rici Jun 22 '20 at 22:45

0 Answers0