In C++ when interrupted with ctrl-c call a function with arguments (other than signal number) before dying

后端 未结 2 1937
后悔当初
后悔当初 2021-02-06 16:54

I want to write a few extra lines to a file when interrupted with ctrl-c before the program dies. However the location of the file is not hard coded so I need something more tha

2条回答
  •  遥遥无期
    2021-02-06 17:41

    Based on the answer to "How can I catch a ctrl-c event? (C++)" we can install a signal handler that simply raises an exception. Then we can catch the exception and run whatever standard c++ code we like.

    Here's a working example:

    #include 
    #include 
    #include 
    #include 
    
    
    class InterruptException : public std::exception
    {
    public:
      InterruptException(int s) : S(s) {}
      int S;
    };
    
    
    void sig_to_exception(int s)
    {
      throw InterruptException(s);
    }
    
    
    int main()
      {
        // Taken from answer to "How can I catch a ctrl-c event? (C++)"
        struct sigaction sigIntHandler;
        sigIntHandler.sa_handler = sig_to_exception;
        sigemptyset(&sigIntHandler.sa_mask);
        sigIntHandler.sa_flags = 0;
        sigaction(SIGINT, &sigIntHandler, NULL);
    
    
        try
          {
            std::cout << "Inside try" << std::endl;
    
            // Do something with output so the loop doesn't get optimised out
            double i = 0;
            while(i < 1e30) {i++;} // loop until interrupted
            std::cout << i << std::endl;
          }
        catch(InterruptException& e)
          {
            std::cout << "Write something to file" << std::endl;
            std::cout << "Caught signal " << e.S << std::endl;
            return 1;
          }
    
        return 0;
      }
    

    This approach does have at least one downside: we have to wrap everything after the handler is installed in a try, otherwise interrupt signals would cause an abort().

提交回复
热议问题