本文最后更新于2017年8月5日,已超过 1 年没有更新,如果文章内容失效,还请反馈给我,谢谢!
=Start=
缘由:
学习需要
正文:
参考解答:
alarm()+signal()/sigaction()实现的不那么精确的定时器功能
#include
#include
#include
#include /* struct timeval */
#include /* time() */
#include
#include
#include
void print_current_time_with_ms(void)
{
long ms; // Milliseconds
time_t s; // Seconds
struct timespec spec;
clock_gettime(CLOCK_REALTIME, &spec);
s = spec.tv_sec;
ms = round(spec.tv_nsec / 1.0e6); // Convert nanoseconds to milliseconds
printf("Current time: %"PRIdMAX".%03ld seconds since the Epoch\n", (intmax_t)s, ms);
}
void sigalrm_fn(int sig)
{
print_current_time_with_ms();
alarm(2);// every 2 seconds
return;
}
int main(void)
{
signal(SIGALRM, sigalrm_fn);
alarm(1);// first call ?
while(1)
pause();
return 0;
}
/* $ ./a.out
Current time: 1501747559.026 seconds since the Epoch
Current time: 1501747561.026 seconds since the Epoch
Current time: 1501747563.028 seconds since the Epoch
Current time: 1501747565.032 seconds since the Epoch
Current time: 1501747567.035 seconds since the Epoch
*/
setitimer()+sigaction()的一个实现
#include
#include
#include
int limit = 10;
/* signal process */
void timeout_info(int signo)
{
if(limit == 0)
{
printf("Sorry, time limit reached.\n");
return;
}
printf("Only %d seconds left.\n", limit--);
}
/* init sigaction */
void init_sigaction(void)
{
struct sigaction act;
act.sa_handler = timeout_info;
act.sa_flags = 0;
sigemptyset(&act.sa_mask);
sigaction(SIGPROF, &act, NULL);
}
/* init */
void init_time(void)
{
struct itimerval val;
val.it_value.tv_sec = 1;
val.it_value.tv_usec = 0;
val.it_interval = val.it_value;
setitimer(ITIMER_PROF, &val, NULL);
}
int main(void)
{
init_sigaction();
init_time();
printf("You have only 10 seconds for thinking.\n");
while(1);
return 0;
}
多个setitimer()的示例
#include
#include
#include
#include
#include
#include
#include
#include
void print_current_time_with_ms(void)
{
long ms; // Milliseconds
time_t s; // Seconds
struct timespec spec;
clock_gettime(CLOCK_REALTIME, &spec);
s = spec.tv_sec;
ms = round(spec.tv_nsec / 1.0e6); // Convert nanoseconds to milliseconds
printf("Current time: %"PRIdMAX".%03ld seconds since the Epoch\n", (intmax_t)s, ms);
}
int sec = 5;
void sigroutine(int signo){
switch (signo) {
case SIGALRM:
printf("Catch a signal -- SIGALRM\n");
print_current_time_with_ms();
signal(SIGALRM, sigroutine);
break;
case SIGVTALRM:
printf("Catch a signal -- SIGVTALRM\n");
print_current_time_with_ms();
signal(SIGVTALRM, sigroutine);
break;
}
return;
}
int main() {
printf("process id is %d\n", getpid());
signal(SIGALRM, sigroutine);
signal(SIGVTALRM, sigroutine);
struct itimerval value, ovalue, value2; //(1)
value.it_value.tv_sec = 1;
value.it_value.tv_usec = 0;
value.it_interval.tv_sec = 1;
value.it_interval.tv_usec = 0;
setitimer(ITIMER_REAL, &value, &ovalue); //(2)
value2.it_value.tv_sec = 0;
value2.it_value.tv_usec = 500000;
value2.it_interval.tv_sec = 0;
value2.it_interval.tv_usec = 500000;
setitimer(ITIMER_VIRTUAL, &value2, &ovalue);
for(;;)
;
return 0;
}
参考链接:
=END=