linux之sleep
linux中的sleep为库调用(library calls),其声明文件为unistd.h。
unsigned int sleep(unsigned int seconds);
如果进程或者线程调用sleep请求的休眠的时间seconds过去,那么会返回0;如果休眠期间被信号中断,那么返回剩余的休眠时间。
#include <unistd.h> #include <stdio.h> #include <signal.h> #include <signal.h> void sig_handler(int num) { printf("receive %d signal\n", num); }
// 在休眠时间20s内,键入中断信号(ctrl+c) int t_main() { int time = 20; signal(SIGINT, sig_handler); printf("enter sleep\n"); sleep(time); printf("sleep over\n"); return 0; }
/*
./xsleep
enter sleep
^Creceive 2 signal
sleep over
*/ int main() { int time = 20; signal(SIGINT, sig_handler); printf("enter sleep\n"); do{ time = sleep(time); }while (time > 0); printf("sleep over\n"); return 0; }
/*
./xsleep
enter sleep
^Creceive 2 signal
^Creceive 2 signal
^Creceive 2 signal
^Creceive 2 signal
^Creceive 2 signal
^Creceive 2 signal
^Creceive 2 signal
sleep over
*/