23 定时器与休眠
定时器 API
1. setitimer
和 getitimer
(不建议)
SYNOPSIS
#include <sys/time.h>
int getitimer(int which, struct itimerval *curr_value);
int setitimer(int which, const struct itimerval *restrict new_value,
struct itimerval *_Nullable restrict old_value);
which
参数指定创建的定时器的类型
- 可以是真实时间,到期的信号是 SIGALARM。
- 可以是用户 CPU 时间(进程虚拟时间),到期的信号为 SIGVTALRM。
- 可以是内核 + 用户 CPU 时间(profiling 定时器),到期的信号是 SIGPROF。
以上三种信号默认行为是终止进程,所以定时器要结合信号处理函数使用。
struct itimerval
参数解释
struct itimerval {
struct timeval it_interval; /* Interval for periodic timer */
struct timeval it_value; /* Time until next expiration */
};
其中 timeval
是带有秒和微秒的结构体,可以参考
10.01 时间类型 tm time_t timeval timespec。