signal 信号处理例子

#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

void cyclic_task()
{
    static long int count = 0;
    while (1)
    {
        sleep(1);
        printf("cyclic_task....\n");
    }
    
}
static unsigned int sig_alarms = 0;

/****************************************************************************/

void signal_handler(int signum)
{
    switch (signum)
    {
        case SIGALRM:                       //收到信号SIGALRM之后,处理
        printf("signal_handler\n");
            break;
    }
}

int main(int argc, char **argv)
{
    struct sigaction sa;
    struct itimerval tv;

    int err;

    /********************************************************************/
    sa.sa_handler = signal_handler;  //信号处理句柄
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    if (sigaction(SIGALRM, &sa, 0)) {         //安装信号处理
        fprintf(stderr, "Failed to install signal handler!\n");
        return -1;
    }
    printf("Starting timer...\n");
    printf("**************Start test************\n");
 
    tv.it_value.tv_sec = 1;             //定时器
    tv.it_value.tv_usec = 0 ;
    tv.it_interval = tv.it_value;

    if (setitimer(ITIMER_REAL, &tv, NULL)) {
        fprintf(stderr, "Failed to start timer: %s\n", strerror(errno));
        return 1;
    }

    cyclic_task();

    /********************************************************************/
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值