在linux编程中,有时候会用到定时功能,常见的是用sleep(time)函数来睡眠time秒;但是这个函数是可以被中断的,也就是说当进程在睡眠的过程中,如果被中断,那么当中断结束回来再执行该进程的时候,该进程会从sleep函数的下一条语句执行;这样的话就不会睡眠time秒了;
1
2
3
4
| #include <unistd.h>
unsigned int sleep (unsigned int seconds);
int usleep (useconds_t usec);
|
参数
返回值
- sleep: 正常结束返回0,中断退出返回剩余时间
- usleep: 正常结束返回0,中断退出返回-1,并设置errno标注原因
示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| #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);
}
|
运行结果
1
2
3
4
| enter to the sleep.
^C
recvive the signal is 2
sleep is over, main over.
|
从运行结果可以看出,当按下Ctrl+c发出中断的时候,被该函数捕获,当处理完该信号之后,函数直接执行sleep下面的语句;
备注:sleep(time)返回值是睡眠剩下的时间;
参考链接
https://www.cnblogs.com/wuyepeng/p/9789466.html