信号的产生(软件条件)
除了常见的信号产生方式,软件条件也可以触发信号。例如,在管道通信中,当读端关闭时,操作系统会向写端发送 SIGPIPE 信号。
alarm 函数
alarm 函数用于设置一个定时器,指定秒数后内核会给进程发送 SIGALRM 信号,默认动作为终止进程。函数返回值是之前设定的剩余秒数。
#include <iostream>
#include <unistd.h>
#include <signal.h>
void handlerSign(int sign) {
std::cout << "获得了一个信号 : " << sign << std::endl;
exit(13);
}
int main() {
for (int i = 1; i < 32; i++) {
signal(i, handlerSign);
}
alarm(1);
int cnt = 0;
while (true) {
std::cout << "cnt : " << cnt++ << std::endl;
}
return 0;
}
上述程序在 1 秒后被 SIGALRM 终止,返回码为 14(即 SIGALRM)。
优化后的计数版本如下:
#include <iostream>
#include <unistd.h>
#include <signal.h>
int cnt = 0;
{
std::cout << << sign << << cnt << std::endl;
();
}
{
(SIGALRM, handlerSign);
();
() {
cnt++;
}
;
}

