C++信号处理

C++信号处理

0、信号分类:

信号分类描述
SIGABRT程序的异常终止,如调用 abort。
SIGFPE错误的算术运算,比如除以零或导致溢出的操作。
SIGILL检测非法指令。
SIGINT接收到交互注意信号。
SIGSEGV非法访问内存。
SIGTERM发送到程序的终止请求。

1、signal() 函数


/*
C++ 信号处理库提供了signal函数,用来捕获突发事件。以下是 signal() 函数的语法:
*/
void (*signal (int sig, void (*func)(int)))(int); 

这个函数接收两个参数:
第一个参数: 一个整数,代表了信号的编号。
第二个参数: 一个指向信号处理函数的指针。

实例:

#include <iostream>
#include <csignal>
#include <stdlib.h>
#include <unistd.h>

using namespace std;

void signalHandler( int signum )
{
    cout << "Interrupt signal ( " << signum << " ) received.\n";
    // 清理并关闭
    // 终止程序  
   exit(signum);    //unistd.h
}
int main ()
{
    // 注册信号 SIGINT 和信号处理程序
    signal(SIGINT, signalHandler);  
    while(1){
       cout << "I am Working Now...." << endl;
       sleep(1);    //stdlib.h
    }
    return 0;
}

2、raise() 函数

/*
使用函数 raise()生成信号,该函数带有一个整数信号编号作为参数,语法如下:
*/
int raise (signal sig);

实例:

#include <iostream>
#include <csignal>
#include <stdlib.h>
#include <unistd.h>

using namespace std;

void signalHandler( int signum )
{
    cout << "Interrupt signal (" << signum << ") received.\n";
    // 清理并关闭
    // 终止程序 
    exit(signum);  
}

int main ()
{
    int i = 0;
    // 注册信号 SIGINT 和信号处理程序
    signal(SIGINT, signalHandler);  

    while(++i){
       cout << "I am Working Now...." << endl;
       if( i == 3 ){
          raise( SIGINT);
       }
       sleep(1);
    }

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值