#include <time.h>
int nanosleep(const struct timespec *req, struct timespec *rem);
struct timespec {
time_t tv_sec; /* 秒 */
long tv_nsec; /* 纳秒 */
};
#include <stdio.h>
#include <time.h>
#include <signal.h>
#include <errno.h>
void sigfunc (int sig_no)
{
int temp = 1000;
while (temp-- > 0)
;
}
int msleep (unsigned long milisec, int temp)
{
struct timespec req = {0}, rem = {0};
time_t sec = (int)(milisec / 1000);
milisec = milisec - (sec * 1000);
req.tv_sec = sec; /*秒*/
req.tv_nsec = milisec * 1000000L; /*纳秒*/
while (nanosleep (&req, &req) == -1 && errno == EINTR) {
printf ("测试-%d被信号中断,剩余时间为: %ld秒%ld纳秒\n", temp, req.tv_sec, req.tv_nsec);
continue;
}
return (1);
}
int main()
{
struct sigaction sa = {0};
sa.sa_handler = &sigfunc;
sigaction (SIGINT, &sa, NULL); //安装信号处理函数
unsigned long a = 0;
int temp = 1;
scanf ("%ld", &a);
for (;;) {
if (a == 5) {
printf ("testing-%d\n", temp);
msleep (a*1000, temp); //将 nanosleep() 封装在 msleep() 中
temp++;
} else
usleep (1000000);
}
return (1);
}
$ ./nanosleep
5
testing-1
testing-2
^C测试-2被信号中断,剩余时间为: 4秒120263116纳秒
^C测试-2被信号中断,剩余时间为: 3秒440359866纳秒
^C测试-2被信号中断,剩余时间为: 2秒320431341纳秒
^C测试-2被信号中断,剩余时间为: 1秒320495448纳秒
testing-3
... ...
欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) | Powered by Discuz! X3.2 |