ในส่วนนี้เราจะดูวิธีเขียนโปรแกรมใน C ที่ไม่สามารถ terminate ด้วย Ctrl + C ได้
Ctrl + C สร้าง keyboard interrupt หยุด execution ของ current process ที่นี่เมื่อกด Ctrl + C จะพิมพ์ข้อความแล้วทำงานต่อ ใช้ signal handling technique ใน C Ctrl + C สร้าง SIGINT signal มี signals อื่นๆ และ functions:
| Signal | Description |
|---|---|
| SIGABRT | Abnormal termination |
| SIGFPE | Floating point exception |
| SIGILL | Invalid instruction |
| SIGINT | Interactive attention request sent to program |
| SIGSEGV | Invalid memory access |
| SIGTERM | Termination request sent to program |
ใช้ standard C library function signal() จัดการ signals นี้
ตัวอย่างโค้ด
#include <stdio.h> #include <signal.h> void sigint_handler(int signum) { //Handler for SIGINT //Reset handler to catch SIGINT next time. signal(SIGINT, sigint_handler); printf("Cannot be stopped using Ctrl+C \n"); fflush(stdout); } main () { signal(SIGINT, sigint_handler); while(1) { //create infinite loop } }ผลลัพธ์
Cannot be stopped using Ctrl+C Cannot be stopped using Ctrl+C