timer_create的简单使用

本文介绍了Linux中两种定时器通知方式:SIGEV_SIGNAL和SIGEV_THREAD。对于SIGEV_SIGNAL,当时间到达时,程序会接收到SIGUSR1信号;而SIGEV_THREAD则会在时间到时创建一个线程执行指定函数。示例代码展示了如何设置和使用这两种通知机制。

一、SIGEV_SIGNAL通知方式

当时间到达时,发送一个信号

#include <stdio.h>
#include <time.h>
#include <signal.h>
#include <unistd.h>


void sigusr1_handler(int sig)
{
	printf("%s---%d\n", __func__, __LINE__);

	return ;
}

int main(void)
{
	int ret;
	timer_t timer_id;
	struct sigevent sev;
	struct itimerspec its;

	signal(SIGUSR1, sigusr1_handler);
	
	sev.sigev_notify = SIGEV_SIGNAL;
	sev.sigev_signo = SIGUSR1;
	sev.sigev_value.sival_ptr = &timer_id;
	ret = timer_create(CLOCK_REALTIME, &sev, &timer_id);
	
	its.it_value.tv_sec = 1;
	its.it_value.tv_nsec = 0;
	its.it_interval.tv_sec = 1;
	its.it_interval.tv_nsec = 0;
	timer_settime(timer_id, 0, &its, NULL);
	
	sleep(2);
	sleep(2);
	
	return 0;
}

二、SIGEV_THREAD通知方式

当时间到达时,创建一个线程

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <signal.h>


void sigalrm_handler(int sig)
{
	printf("%s---%d\n", __func__, __LINE__);
	
	return ;
}



int main(int argc, char *argv[])
{
	int ret;
	timer_t timer_id;
	struct sigevent sev;
	struct itimerspec its;
	
	memset(&sev, 0, sizeof(struct sigevent));
	sev.sigev_notify = SIGEV_THREAD;
	sev.sigev_notify_function = thread_start;
	sev.sigev_value.sival_ptr = &timer_id;
	sev.sigev_value.sival_int = 3;
	ret = timer_create(CLOCK_REALTIME, &sev, &timer_id);
	
	its.it_value.tv_sec = 1;
	its.it_value.tv_nsec = 0;
	its.it_interval.tv_sec = 1;
	its.it_interval.tv_nsec = 0;
	timer_settime(timer_id, TIMER_ABSTIME, &its, NULL);
	
	sleep(10);
	
	
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值