std::signal - jednorazowy signal handler?

0

Witam.

Potrzebuję zablokować użytkownikowi możliwość wyłączania programu za pomocą Ctrl+C.
Niby wszystko spoko:

#include <csignal>
...
void SignalHandler(int signal){
    std::cout<<'['<<signal<<']';
}

int main(){
    std::signal(SIGINT, SignalHandler);
...

Ale gdy raz wysyłam sygnał Ctrl+C, to wypisuje [2], jednakże za drugim razem można bez problemu wyłączyć program.
Dlaczego tak jest i co można z tym zrobić?

Pozdrawiam.

PS taki najprostszy kod obrazujący:

#include <csignal>
#include <iostream>
#include <chrono>
#include <thread>

void SignalHandler(int signal){
    std::cout<<'['<<signal<<']';
}

int main(){
    std::signal(SIGINT, SignalHandler);
    while(1){
        std::cout<<"Blah blah.\n";
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }
}

Wersja g++:

g++ (i686-posix-dwarf-rev0, Built by MinGW-W64 project) 7.3.0
Copyright (C) 2017 Free Software Foundation, Inc.
Kompilacja:
g++ -std=c++1z -Wall -Wextra -O3 -pedantic-errors main.cpp

0

u mnie działa ;)(linux) A z ciekawości zobacz na msvc.

1

Że działa tylko raz może być normalne:

   In the original UNIX systems, when a handler that was established
   using signal() was invoked by the delivery of a signal, the disposi‐
   tion of the signal would be reset to SIG_DFL, and the system did not
   block delivery of further instances of the signal.  This is equiva‐
   lent to calling sigaction(2) with the following flags:

       sa.sa_flags = SA_RESETHAND | SA_NODEFER;

   System V also provides these semantics for signal().  This was bad
   because the signal might be delivered again before the handler had a
   chance to reestablish itself.  Furthermore, rapid deliveries of the
   same signal could result in recursive invocations of the handler.
0

Jeśli poczytać dokumentację, to Twój program ma UB.

Handler powinien mieć linkage C, oraz, co ważniejsze, w przypadku sygnałów asynchronicznych nie ma prawa korzystać z praktycznie całej biblioteki standardowej.

0

Hasło: "c++ control-c"
Wynik nr 3:
http://zguide.zeromq.org/cpp:interrupt

1 użytkowników online, w tym zalogowanych: 0, gości: 1