Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

การจับ Ctrl+C Event ใน C++

Ctrl+C ส่งสัญญาณ SIGINT ให้ process ใช้ signal() จาก <signal.h> จับและจัดการได้

โค้ดตัวอย่าง

#include <iostream>
#include <signal.h>
#include <unistd.h>
#include <cstdlib>
using namespace std;

void signal_handler(int signum) {
    cout << "Caught signal " << signum << endl; // signum = 2 (SIGINT)
    exit(signum); // จบโปรแกรม
}

int main() {
    signal(SIGINT, signal_handler); // ลงทะเบียน handler
    while (true) {
        cout << "Processing...\n";
        sleep(1);
    }
}

ผลลัพธ์

Processing...
Processing...
^Caught signal 2
# โปรแกรมจบ

ข้อควรระวัง

  • Signal handler ควรทำให้น้อยที่สุด (async-signal-safe functions เท่านั้น)
  • หลายระบบ ใช้ sigaction() แทน signal() เพื่อ portability
  • C++ ไม่มี signal handling มาตรฐานใน library (ใช้ C library)