Linux C定時器使用

來源:互聯網
上載者:User

標籤:style   http   color   io   os   ar   使用   sp   div   

  zhanhailiang 日期:2014-10-25
原理

Linux為每個進程提供3種定時器:

  1. ITIMER_REAL: 以系統真實的時間來計算,它送出SIGALRM訊號。
  2. ITIMER_VIRTUAL: 以該進程在使用者態下花費的時間來計算,它送出SIGVTALRM訊號。
  3. 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定時器使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.