-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEx_23_2.c
79 lines (63 loc) · 2.52 KB
/
Ex_23_2.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*************************************************************************\
* Copyright (C) Michael Kerrisk, 2024. *
* *
* This program is free software. You may use, modify, and redistribute it *
* under the terms of the GNU General Public License as published by the *
* Free Software Foundation, either version 3 or (at your option) any *
* later version. This program is distributed without any warranty. See *
* the file COPYING.gpl-v3 for details. *
\*************************************************************************/
/* t_nanosleep.c
Demonstrate the use of clock_nanosleep() to sleep for an interval
specified in nanoseconds.
See also t_clock_nanosleep.c.
*/
#define _POSIX_C_SOURCE 199309
#include <sys/time.h>
#include <time.h>
#include <signal.h>
#include "tlpi_hdr.h"
static void
sigintHandler(int sig)
{
return; /* Just interrupt clock_nanosleep() */
}
int
main(int argc, char *argv[])
{
struct timeval start, finish;
struct timespec request, remain;
struct sigaction sa;
struct timespec tp;
int s;
if (argc != 3 || strcmp(argv[1], "--help") == 0)
usageErr("%s secs nanosecs\n", argv[0]);
if (clock_gettime(CLOCK_REALTIME, &tp) == -1)
errExit("clock_gettime");
request.tv_nsec = tp.tv_nsec + getLong(argv[2], 0, "nanosecs");
request.tv_sec = tp.tv_sec + getLong(argv[1], 0, "secs") +
request.tv_nsec/1000000000;
request.tv_nsec %= 1000000000;
/* Allow SIGINT handler to interrupt clock_nanosleep() */
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = sigintHandler;
if (sigaction(SIGINT, &sa, NULL) == -1)
errExit("sigaction");
if (gettimeofday(&start, NULL) == -1)
errExit("gettimeofday");
for (;;) {
s = clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &request, &remain);
if (s == -1 && errno != EINTR)
errExit("nanosleep");
if (gettimeofday(&finish, NULL) == -1)
errExit("gettimeofday");
printf("Slept for: %9.6f secs\n", finish.tv_sec - start.tv_sec +
(finish.tv_usec - start.tv_usec) / 1000000.0);
if (s == 0)
break; /* clock_nanosleep() completed */
printf("Remaining: %2ld.%09ld\n", (long) remain.tv_sec, remain.tv_nsec);
}
printf("Sleep complete\n");
exit(EXIT_SUCCESS);
}