Commit f0334279 authored by Administrator's avatar Administrator
Browse files

add signal and preprocessor

parent 06e83b5a
#include <iostream>
// 预处理器用于在编译前修改代码
// 用途1: 宏定义,在编译前将所有的 PI 替换为3.14159
#define PI 3.14159
// 用途2: 条件编译
#define DEBUG
// 用途3: #运算符
// "#x"代表将x作为字符串
#define MKSTR(x) #x
// 用途4: ##运算符
// 在编译时将两个参数的名称拼接起来,"x ## y"被拼接为xy
#define CONCAT(x, y) x ## y
using namespace std;
int main () {
// 用途1: 宏定义,在编译前将所有的 PI 替换为3.14159
cout << "Value of PI :" << PI << endl;
// 用途2: 条件编译
#ifdef DEBUG
// 如果预定义过DEBUG,那么编译下面的代码
cout << "DEBUG Mode" << endl;
#endif
// 用途3: 将括号中的"HELLO WORLD!"作为字符串
cout << MKSTR(HELLO WORLD!) << endl;
// 用途4: 在编译时将两个参数的名称拼接起来,"x ## y"被拼接为xy
int xy = 100;
cout << CONCAT(x, y) << endl;
// 默认的预定义
// __LINE__: 代码的行号
cout << "Value of __LINE__ : " << __LINE__ << endl;
// __FILE__: 代码的文件名
cout << "Value of __FILE__ : " << __FILE__ << endl;
// __DATE__: 当前日期 Mon DD YYYY
cout << "Value of __DATE__ : " << __DATE__ << endl;
// __LINE__: 时间戳 HH:MI:SS
cout << "Value of __TIME__ : " << __TIME__ << endl;
return 0;
}
\ No newline at end of file
// C++可处理的信号
// SIGABRT: 程序的异常终止,如调用 abort。
// SIGFPE: 错误的算术运算,比如除以零或导致溢出的操作。
// SIGILL: 检测非法指令。
// SIGINT: 接收到交互注意信号。
// SIGSEGV: 非法访问内存。
// SIGTERM: 发送到程序的终止请求。
// SIGBUS: Bus error which indicates access to an invalid address
// SIGALRM: This is used by the alarm() function and indicates the expiration of the timer. 超时警告
// SIGABRT: Termination of a program, abnormally
// SIGSTOP: The signal cannot be blocked, handled, and ignored and can stop a process
// SIGUSR1: 用户定义信号
// SIGSUR2: 用户定义信号
// 用法:
// void (*signal (int sig, void (*func)(int)))(int);
// signal(registered signal, signal handler)
#include <iostream>
#include <csignal>
#include <unistd.h>
using namespace std;
// 定义信号处理函数
// 必须是 void func(int) 的形式
void signalHandler(int signum) {
cout << "Interrupt signal (" << signum << ") received." << endl;
// 清理并关闭
// 终止程序
exit(signum);
}
int main() {
// 注册信号 SIGINT 和信号处理程序
signal(SIGINT, signalHandler);
while(true) {
cout << "Going to sleep...." << endl;
sleep(1);
}
return 0;
}
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment