Override Ctrl-C

前端 未结 2 1872
一整个雨季
一整个雨季 2020-12-10 13:00

I am supposed override the CtrlC signal and use it to print a message. It is not supposed to end the program.

What happens so far is that when

相关标签:
2条回答
  • 2020-12-10 13:46

    Whoa, way too much code to sift through. However, if you use the C standard library, you should get the desired behaviour. Here's a C++ version:

    #include <iostream>
    #include <csignal>
    
    sig_atomic_t sigflag = 0;
    
    void sighandler(int s)
    {
      // std::cerr << "Caught signal " << s << ".\n"; // this is undefined behaviour
      sigflag = 1; // something like that
    }
    
    int main()
    {
      std::signal(SIGINT, sighandler);
    
      // ... your program here ...
    
      // example: baby's first loop (Ctrl-D to end)
      char c;
      while (std::cin >> c)
      {
        if (sigflag != 0) { std::cerr << "Signal!\n"; sigflag = 0; }
      }
    }
    

    This will catch Ctrl-C (which raises SIGINT), and the signal handler is not replaced, so it'll fire every time, and nobody is terminating the program.

    Note that signal handlers are inherited by fork()ed children.

    The Posix function sigaction() allows you to register "one-shot" handlers which are replaced by the standard handler after they're invoked once. That's more advanced and Posix-specific, though.

    Edit: As @Dietrich points out, you should never do any real work inside a signal handler. Rather, you should set a flag (I provided an example), and check for that flag inside your loop (and print the message there). I'll amend the example for that, too.

    0 讨论(0)
  • 2020-12-10 13:55

    Have you considered that inside your while loop there may be an interruptable function failing with 'EINTR'. You could might be able to fix it by using :

    sa.sa_flags = SA_RESTART;
    

    Or, just checking errno for it and looping. Are you sure the program isn't reaching the end of termination. Try putting a print statement at the end of main.

    0 讨论(0)
提交回复
热议问题