Skip to content

Instantly share code, notes, and snippets.

@corvofeng
Created March 29, 2018 13:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save corvofeng/ef15bcc10e083b5f408bda25eb8b7f07 to your computer and use it in GitHub Desktop.
Save corvofeng/ef15bcc10e083b5f408bda25eb8b7f07 to your computer and use it in GitHub Desktop.
使用Linux中的信号, 每隔三秒发送一次定时启动handler函数
/* ch14-timers.c ---- demonstrate interval timers */
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <signal.h>
#include <sys/time.h>
/* handler --- handle SIGALRM */
struct itimerval tval;
void handler(int signo)
{
static const char msg[] = "\n*** Timer expired, you lose ***\n";
assert(signo == SIGALRM);
printf("%s\n", msg);
(void) setitimer(ITIMER_REAL, &tval, NULL);
// exit(1);
}
/* main --- set up timer, read data with timeout */
int main(void)
{
char string[BUFSIZ];
timerclear(& tval.it_interval); /* zero interval means no reset of timer */
timerclear(& tval.it_value);
tval.it_value.tv_sec = 3; /* 3 second timeout */
(void) signal(SIGALRM, handler);
(void) setitimer(ITIMER_REAL, & tval, NULL);
while(1);
exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment