每天一个Linux命令(sleep&usleep)

    • sleep及usleep命令简介
    • 具体实现
    • 使用

sleep及usleep命令简介

sleep命令能够产生以秒为单位的脚本挂起时间
usleep命令能够产生以微妙(百万分之一秒)为单位的脚本挂起时间

具体实现

linux中的sleep和usleep的实现是调用unistd.h头文件中的
unsigned sleep(unsigned)int usleep(unsigned long)两个函数实现的。

下面给出sleep命令的简易实现:

int main(int argc,char* argv[]){
    if(argc<2){
        show_usage();
    }
    sleep(atoi(*(++argv)));
    return 0;
}

usleep命令的简易实现:

int main(int argc,char* argv[]){
    if(argc<2){
        show_usage();
    }
    usleep(atoi(*(++argv)));
    return 0;
}

使用

在编写shell脚本时候,如果希望在执行一个命令之后,等待几秒(或几微妙)之后再去执行另外一个命令,这个时候就可以在这两个命令之间插入一条sleep语句来挂起脚本执行。
sleepusleep的语法:sleep(usleep) time
这里的time就是你需要脚本挂起的时间,其中sleep命令的挂起时间单位为秒,usleep命令的挂起时间单位为微妙。
如:

    echo "hello,world1">>testfile
    sleep 2
    echo "hello,world2">>testfile

上述脚本是将hello,world1字符串输出到testfile文件后,隔2秒钟后再将hello,world2字符串输出到testfile文件。

在使用sleep时也有一点也需要特别注意,就是脚本中的sleep语句后不要跟有&符号,不然sleep是不会起作用的。

    echo "hello,world">>testfile
    sleep 2 &
    echo "hello,world">>testfile

可以把上述命令写到脚本里并执行,发现脚本并不会挂起2秒再写文件,读者可以想想是为什么?

你可能感兴趣的:(linux-shell)