zoukankan      html  css  js  c++  java
  • linux中sleep函数的使用和总结

    在linux编程中,有时候会用到定时功能,常见的是用sleep(time)函数来睡眠time秒;但是这个函数是可以被中断的,也就是说当进程在睡眠的过程中,如果被中断,那么当中断结束回来再执行该进程的时候,该进程会从sleep函数的下一条语句执行;这样的话就不会睡眠time秒了;

    头文件: #include <unistd.h>
    函数:unsigned int sleep (unsigned int seconds);//n秒
    此外:int usleep (useconds_t usec);//n微秒
     
    例子:
    #include<stdio.h>
    #include <stdlib.h>
    #include <signal.h>
    #include <unistd.h>
     
    void sig_handler(int num)
    {
        printf("
    recvive the signal is %d
    ", num);
    }
     
    int main()
    {
        int time = 20;
     
        signal(SIGINT, sig_handler);
        printf("enter to the sleep.
    ");
     
        sleep(time);  
     
        printf("sleep is over, main over.
    ");
     
        exit(0);
    }
    

    运行结果截图如下:

    从运行结果可以看出,当我按下Ctrl+c发出中断的时候,被该函数捕获,当处理完该信号之后,函数直接执行sleep下面的语句;
    备注:sleep(time)返回值是睡眠剩下的时间;

    下面的例子是真正的睡眠time时间(不被中断影响):

    #include<stdio.h>
    #include <stdlib.h>
    #include <signal.h>
    #include <unistd.h>
     
    void sig_handler(int num)
    {
        printf("
    recvive the signal is %d
    ", num);
    }
     
    int main()
    {
        int time = 20;
     
        signal(SIGINT, sig_handler);
        printf("enter to the sleep.
    ");
        //sleep(time);
        do{
            time = sleep(time);
        }while(time > 0);
     
        printf("sleep is over, main over.
    ");
     
        exit(0);
    }
    

    运行结果截图如下:

    备注:其中recevie the signal is 2.表示该信号是中断信号;信号的具体值如下图所示:

    最后是sleep函数的man手册,命令为:man 3 sleep

     

  • 相关阅读:
    linux shell基本知识
    chkconfig命令 centos 开机启动命令
    centos 7修改网卡名称
    centos 系统安装基本步骤,面试必考
    nginx 服务脚本编写模板
    nginx 服务脚本编写模板
    Mysql 多实例实施步骤
    shell常用监控脚本
    nginx做负载均衡 tomcat获得客户端真实ip
    vmvare安装系统提示vmci.sys 版本不正确解决方法
  • 原文地址:https://www.cnblogs.com/wuyepeng/p/9789466.html
Copyright © 2011-2022 走看看