定时器
信号定时器的方法和epoll一起,会导致程序正常退出。
- 头文件
#include <signal.h>
#include <time.h>
- 创建定时器
int timer_create(clockid_t clockid, struct sigevent *evp, timer_t *timerid);
-
- clockid取值
CLOCK_REALTIME | 可设定的系统级实时时钟 | 用的最多 |
CLOCK_MONOTONIC |
不可设定的恒定态时钟 | 适用于无法容忍系统时钟发生跳跃性变化的应用程序 |
CLOCK_MONOTONIC_RAW(Linux 2.6.28) |
提供了对纯基于硬件时间的访问,不受NTP时间调整的影响 | 该非标准时钟适用于专业时钟同步应用程序 |
CLOCK_PROCESS_CPUTIME_ID | 每进程CPU时间的时钟 | |
CLOCK_THREAD_CPUTIME_ID | 每线程CPU时间的时钟 |
- struct sigevent
union sigval { int sival_int; void *sival_ptr; }; struct sigevent { int sigev_notify; int sigev_signo; union sigval sigev_value; union { pid_t _tid; /* 2 */ struct { void (*_function) (union sigval); /* 1 */ void *_attribute; } _sigev_thread; } _sigev_un; };
-
- sigev_notify取值
SIGEV_NONE | 不通知 |
SIGEV_SIGNAL | 发送sigev_signo信号给进程 |
SIGEV_THREAD | 调用func 1 |
SIGEV_THREAD_ID | fasong sigev_signo给tid 2标识的线程 |
- 启动/停止定时器
int timer_settime(timer_t timerid, int flags, const struct itimerspec *value, struct itimerspec *old_value); /* 1 */
- struct itimerspec
struct itimerspec { struct timespec it_interval; struct timespec it_value; }; struct timespec { time_t tv_sec; long tv_nsec; };
- value 1设定
只运行一次 | 只设置it_value |
周期运行 | 设置it_interval为周期,设置it_value为首次运行时间;周期运行实现的机制是,用it_interval替换it_value |
- flag设置
TIMER_ABSTIME | value1是一个绝对时间 |
- 测试代码
#include <signal.h> #include <time.h> #include <string.h> #include <stdio.h> void timeUp(int a) { printf("This is func for process sig: %d.\n", a); } int main(void) { clockid_t clockid = CLOCK_REALTIME; struct sigevent ev; timer_t timerid; /* 不用初始化,返回时设置,之后使用 */ int flags = 0; struct itimerspec value; struct timespec *p; struct sigaction sa; bzero(&ev, sizeof(struct sigevent)); bzero(&value, sizeof(struct itimerspec)); bzero(&sa, sizeof(struct sigaction)); sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sa.sa_handler = timeUp; sigaction(SIGUSR1, &sa, NULL); ev.sigev_notify = SIGEV_SIGNAL; ev.sigev_signo = SIGUSR1; // ev.sigev_value.sival_ptr = ; //ev._sigev_thread = ; timer_create(clockid, &ev, &timerid); p = &(value.it_value); p->tv_sec = 2; p = &(value.it_interval); p->tv_sec = 5; timer_settime(timerid, flags, &value, NULL); while(1) { 3; } return 0; }
- 编译
gcc timer.c -lrt
posted on 2021-04-25 17:31 toughcactus 阅读(76) 评论(0) 编辑 收藏 举报