Search code examples
c++ctrl

Cancel CTRL+C while system() is executing [C++]


How can I make CTRL+C not do anything when I'm currently doing system().

This is my code:

#include <iostream>
#include <functional>
#include <signal.h>
void noCTRLCCancel(int sig) {
    signal(SIGINT, noCTRLCCancel);
    std::cout << "CTRL+C pressed, not shutting down." << std::endl;
}
inline void command() {
    system("some command"); // When CTRL+C is pressed, it cancels the command, but how to cancel CTRL+C and do nothing?
}
int main(int argc, char **argv) {
    signal(SIGINT, noCTRLCCancel);
    command();
}

Solution

  • You can ignore a specific signal with SIG_IGN and set it back to default with SIG_DFL.

    void command() {
        std::signal(SIGINT, SIG_IGN);
        system("some command");
        std::signal(SIGINT, SIG_DFL);
    }
    

    https://en.cppreference.com/w/cpp/utility/program/signal