linux中sleep详解实例

来源:互联网 发布:乔丹在奇才队的数据 编辑:程序博客网 时间:2024/06/05 16:16

在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

1 0
原创粉丝点击