Posted on 2008-08-18 18:55
Prayer 閱讀(6774)
評論(0) 編輯 收藏 引用 所屬分類:
LINUX/UNIX/AIX
alarm(設(shè)置信號傳送鬧鐘)
相關(guān)函數(shù) signal,sleep
表頭文件 #include<unistd.h>
定義函數(shù) unsigned int alarm(unsigned int seconds);
函數(shù)說明 alarm()用來設(shè)置信號SIGALRM在經(jīng)過參數(shù)seconds指定的秒數(shù)后傳送給目前的進(jìn)程。如果參數(shù)seconds 為0,則之前設(shè)置的鬧鐘會被取消,并將剩下的時間返回。
返回值 返回之前鬧鐘的剩余秒數(shù),如果之前未設(shè)鬧鐘則返回0。
代碼
#include<unistd.h>
#include<signal.h>
void handler() {
printf("Hello\n");
signal(SIGALRM,handler);讓內(nèi)核做好準(zhǔn)備,一旦接受到SIGALARM信號,就執(zhí)行 handler
alarm(5);
}/*這段函數(shù)的執(zhí)行時間不計(jì)算在for循環(huán)的時間之內(nèi)*/
main()
{
int i;
handler();
for(i=1;i<21;i++){
printf("sleep %d ...\n",i);
sleep(1);
}
}
結(jié)果:剛開始在main中執(zhí)行一次,然后每隔5秒執(zhí)行一次handler()
Hello
sleep 1 ...
sleep 2 ...
sleep 3 ...
sleep 4 ...
sleep 5 ...
Hello
sleep 6 ...
sleep 7 ...
sleep 8 ...
sleep 9 ...
sleep 10 ...
Hello
sleep 11 ...
sleep 12 ...
sleep 13 ...
sleep 14 ...
sleep 15 ...
Hello
sleep 16 ...
sleep 17 ...
sleep 18 ...
sleep 19 ...
sleep 20 ...
Hello