C++

C++ 常用操作

Posted by shensunbo on August 28, 2024
  1. 使用signal机制, 来捕获CTRL + C, 以使while(1)类的循环正常终止,正常情况下使用ctrl + c杀死程序,并不会调用析构函数,对有些库和框架可能会出问题
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    
     #include <csignal>
     #include <iostream>
    
     static bool running = true;
    
     static void sigint_handler(int signum) {
         running = false;
     }
    
     int main() {
         signal(SIGINT, sigint_handler);
    
         while (running) {
             // your program logic here
         }
    
         std::cout << "Program ended normally." << std::endl;
         return 0;
     }