alarm()函數說明
1.引用頭文件:#include <unistd.h>;
2.函數標准式:unsigned int alarm(unsigned int seconds);
3.功能與作用:alarm()函數的主要功能是設置信號傳送鬧鍾,即用來設置信號SIGALRM在經過參數seconds秒數后發送給目前的進程。如果未設置信號SIGALARM的處理函數,那么alarm()默認處理終止進程。
4.函數返回值:如果在seconds秒內再次調用了alarm函數設置了新的鬧鍾,則后面定時器的設置將覆蓋前面的設置,即之前設置的秒數被新的鬧鍾時間取代;當參數seconds為0時,之前設置的定時器鬧鍾將被取消,並將剩下的時間返回。
alarm()測試1.1
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> void sig_handler(int num) { printf("receive the signal %d.\n", num); } int main() { signal(SIGALRM, sig_handler); //SIGALRM是在定時器終止時發送給進程的信號 alarm(2); pause();//pause()函數使該進程暫停讓出CPU exit(0); }
運行結果:兩秒鍾后輸出
如果我們想程序每2秒都定時一下,這樣實現也很簡單,我們在處理定時信號的函數中再次定時2秒;實例如下:
#include<stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> void sig_handler(int num) { printf("receive the signal %d.\n", num); alarm(2); } int main() { signal(SIGALRM, sig_handler); alarm(2); while(1)//做一個死循環,防止主線程提早退出,相等於線程中的join { pause(); } //pause();//如果沒有做一個死循環則只會讓出一次cpu然后就還給主線程,主線程一旦運行結束就會退出程序 exit(0); }
運行結果:每隔2秒鍾就會輸出一次。
可以看出程序每隔2秒就會收到信號14,也就是SIGALRM信號;並且當處理完該信號之后,直接執行pause()函數下面的語句;說明pause()是可被中斷的暫停;
備注:這樣就可以使用alarm函數來實現server和client之間的定時通信,比如說我想在一個小時后發送xxx給xxx