linux中sleep詳解例項

readyao發表於2015-11-24

在linux程式設計中,有時候會用到定時功能,常見的是用sleep(time)函式來睡眠time秒;但是這個函式是可以被中斷的,也就是說當程式在睡眠的過程中,如果被中斷,那麼當中斷結束回來再執行該程式的時候,該程式會從sleep函式的下一條語句執行;這樣的話就不會睡眠time秒了;

例項如下:

/*************************************************************************
    > File Name: sleep.c
    > Author:
    > Mail:
    > Created Time: 2015年11月20日 星期五 20時38分59秒
 ************************************************************************/
 
#include<stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
 
void sig_handler(int num)
{
    printf("\nrecvive the signal is %d\n", num);
}
 
int main()
{
    int time = 20;
 
    signal(SIGINT, sig_handler);
    printf("enter to the sleep.\n");
 
    sleep(time);  
 
    printf("sleep is over, main over.\n");
 
    exit(0);
}


從執行結果可以看出,當我按下Ctrl+c發出中斷的時候,被該函式捕獲,當處理完該訊號之後,函式直接執行sleep下面的語句;
備註:sleep(time)返回值是睡眠剩下的時間;

下面的例子是真正的睡眠time時間(不被中斷影響):

/*************************************************************************
    > File Name: sleep.c
    > Author:
    > Mail:
    > Created Time: 2015年11月20日 星期五 20時38分59秒
 ************************************************************************/
 
#include<stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
 
void sig_handler(int num)
{
    printf("\nrecvive the signal is %d\n", num);
}
 
int main()
{
    int time = 20;
 
    signal(SIGINT, sig_handler);
    printf("enter to the sleep.\n");
    //sleep(time);
    do{
        time = sleep(time);
    }while(time > 0);
 
    printf("sleep is over, main over.\n");
 
    exit(0);
}


備註:其中recevie the signal is 2.表示該訊號是中斷訊號;訊號的具體值如下圖所示:

最後可以檢視sleep函式的man手冊,命令為:man 3 sleep

相關文章