2013-10-21 64 views
0

我想定期運行一個函數,給定一個時間步。什麼是最有效的方法來做到這一點?如何等待時間過期

我知道我可以使用一段時間的樣子,只是繼續檢查,直到dt時間過去。但我想知道是否有更好,更高效/優雅的功能使用。

我正在研究虛擬計時器和sigaction。使用這種方法,我會讓sigaction處理程序在時間已過時設置一個標誌,但我仍然需要在while循環中檢查該標誌是否設置在我的主函數中。另外我想知道是否我真的可以讓處理程序運行該函數,但是接下來我必須傳遞很多參數,並且據我所知,處理程序不接受參數,所以我將不得不使用大量全局變量。

解決此問題的最佳方法是什麼?

+0

看到[這個答案](http://stackoverflow.com/a/19447667/841108)到一個非常類似的問題。 –

回答

0

上* IX'ish系統,你可以

  • 安裝一個處理程序SIGALRM,它什麼都不做
  • 設置使用alarm()
  • 呼叫阻塞pause()

如果報警報警信號發送pause()將返回並且

  • 可以運行有問題的功能,在調用pause()

#define _POSIX_SOURCE 1 

#include <stdlib.h> 
#include <stdio.h> 
#include <string.h> 
#include <unistd.h> 
#include <signal.h> 
#include <errno.h> 

void handler_SIGALRM(int signo) 
{ 
    signo = 0; /* Get rid of warning "unused parameter ‘signo’" (in a portable way). */ 

    /* Do nothing. */ 
} 

int main() 
{ 
    /* Override SIGALRM's default handler, as the default handler might end the program. */ 
    { 
    struct sigaction sa; 
    memset(&sa, 0, sizeof(sa)); 

    sa.sa_handler = handler_SIGALRM; 

    if (-1 == sigaction(SIGALRM, &sa, NULL)) 
    { 
     perror("sigaction() failed"); 
     exit(EXIT_FAILURE); 
    } 
    } 

    while (1) 
    { 
    alarm(2); /* Set alarm to occur in two seconds. */ 

    pause(); /* The call blocks until a signal is received; in theis case typically SIGARLM. */ 

    /* Do what is to be done every 2 seconds. */ 
    } 

    return EXIT_SUCCESS; 
} 
0

最簡單的方法是使用sleepusleep,如unistd.h中所定義。

如果這兩種都不可用,那麼常見的解決方法是在沒有文件描述符時使用帶有超時的select

0

包括time.h中,並使用睡眠功能一樣

  • 重新設置報警
  • 啓動
    #include <time.h> 
    #include <stdio.h> 
    #include<windows.h> 
    #include <conio.h> 
    
    int main() { 
        printf("I am going to wait for 4 sec"); 
        Sleep(4000); //sleep for 4000 microsecond= 4 second 
        printf("Finaaly the wait is over"); 
        getch(); 
        return 0; 
    } 
    

    它會給喲你在微秒級別上有精確的延遲。 希望它有幫助。