原理很简单,就是像闹钟一样,隔一段时间就滴答一次,可以设置时间间隔的。
- #include <apue.h>
- static volatile sig_atomic_t sigalrm;
- static void sig_alrm(int signo)
- {
- sigalrm = 1;
- write(STDERR_FILENO, "\a", 2);
- }
- int main(int argc, char **argv)
- {
- int nsec;
- sigset_t set;
- struct sigaction act;
- struct itimerval timer;
- if (argc != 2)
- err_quit("argc == 2");
- daemon(0, 1);
- nsec = atoi(argv[1]);
-
- timer.it_value.tv_sec = nsec;
- timer.it_value.tv_usec = 0;
- timer.it_interval.tv_sec = nsec;
- timer.it_interval.tv_usec = 0;
-
- if (setitimer(ITIMER_REAL, &timer, NULL))
- err_sys("setitimer error");
-
- if (sigemptyset(&set) < 0)
- err_sys("sigemptyset error");
- if (sigaddset(&set, SIGALRM) < 0)
- err_sys("sigaddset error");
- if (sigprocmask(SIG_BLOCK, &set, NULL) < 0)
- err_sys("sigprocmask error");
-
- if (sigemptyset(&set) < 0)
- err_sys("sigemptyset error");
- act.sa_flags = 0;
- act.sa_handler = sig_alrm;
-
- if (sigemptyset(&act.sa_mask) < 0)
- err_sys("sigemptyset error");
- if (sigaction(SIGALRM, &act, NULL) < 0)
- err_sys("sigaction error");
- for ( ; ; ) {
- sigsuspend(&set);
- if (sigalrm) {
- sigalrm = 0;
- }
- }
- return 0;
- }
阅读(1666) | 评论(0) | 转发(0) |