標籤:style http color io os ar 使用 sp div
zhanhailiang 日期:2014-10-25
原理
Linux為每個進程提供3種定時器:
- ITIMER_REAL: 以系統真實的時間來計算,它送出SIGALRM訊號。
- ITIMER_VIRTUAL: 以該進程在使用者態下花費的時間來計算,它送出SIGVTALRM訊號。
- ITIMER_PROF: 以該進程在使用者態下和核心態下所費的時間來計算,它送出SIGPROF訊號。
其通過setitimer來初始化:
int sigaction(int signum,const struct sigaction *act ,struct sigaction *oldact);
設定定時器後在當前進程終止前每隔固定時間都會發送相應的訊號。
此時我們通過sigaction來接收相應訊號並處理相應邏輯:
int sigaction(int signum,const struct sigaction *act ,struct sigaction *oldact);
Demo
如下舉例說明如何使用Linux定時器定時輸出一段文本:
#include <sys/time.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <signal.h>#include <string.h> #define PROMPT "2 seconds over\n\a" char *prompt = PROMPT;unsigned int len; void prompt_info (int signo) { write (STDERR_FILENO, prompt, len);} /* * 設定收到SIGPROF訊號的處理方式為prompt_info,列印一段文本 */void init_sigaction (void) { struct sigaction act; act.sa_handler = prompt_info; act.sa_flags = 0; sigemptyset (&act.sa_mask); sigaction (SIGPROF, &act, NULL);} /* * 設定ITIMER_PROF類型的定時器, 每隔2秒發送一次SIGPROF訊號 */void init_time () { struct itimerval value; value.it_value.tv_sec = 2; value.it_value.tv_usec = 0; value.it_interval = value.it_value; setitimer (ITIMER_PROF, &value, NULL);} int main () { len = strlen (prompt); init_sigaction (); init_time (); while (1); exit (0);}
編譯執行如下:
[root@~/wade/codeReview/learningc/10]# gcc interval.c -o interval[root@~/wade/codeReview/learningc/10]# ./interval 2 seconds over2 seconds over2 seconds over2 seconds over2 seconds over^C[root@~/wade/codeReview/learningc/10]#
參考閱讀
Linux作業系統下C語言編程入門:http://wenku.baidu.com/link?url=pqkDmO8ibRGlaTVfHLe-CjBv4eOglm_9mgaKfuux5S2LHk_80EO5ZZpBUeTibs4Eo1-6_rXSmcUSo1qQ8XkExR9kX6ulqf7h1yTSfmV4le_
Linux C定時器使用