46ec61cd092397ea42fb3adbb63e78186de7d20b
[lttng-tools.git] / tests / utils / utils.c
1 /*
2 * Copyright (C) 2015 Jérémie Galarneau <jeremie.galarneau@efficios.com>
3 *
4 * SPDX-License-Identifier: LGPL-2.1-only
5 *
6 */
7
8 #include <assert.h>
9 #include <common/compat/time.h>
10 #include <common/time.h>
11 #include <errno.h>
12 #include <fcntl.h>
13 #include <poll.h>
14 #include <stdbool.h>
15 #include <stdint.h>
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <sys/stat.h>
19 #include <sys/types.h>
20 #include <unistd.h>
21
22 #include "utils.h"
23
24 static inline
25 int64_t elapsed_time_ns(struct timespec *t1, struct timespec *t2)
26 {
27 struct timespec delta;
28
29 assert(t1 && t2);
30 delta.tv_sec = t2->tv_sec - t1->tv_sec;
31 delta.tv_nsec = t2->tv_nsec - t1->tv_nsec;
32 return ((int64_t) NSEC_PER_SEC * (int64_t) delta.tv_sec) +
33 (int64_t) delta.tv_nsec;
34 }
35
36 int usleep_safe(useconds_t usec)
37 {
38 int ret = 0;
39 struct timespec t1, t2;
40 int64_t time_remaining_ns = (int64_t) usec * (int64_t) NSEC_PER_USEC;
41
42 ret = lttng_clock_gettime(CLOCK_MONOTONIC, &t1);
43 if (ret) {
44 ret = -1;
45 perror("clock_gettime");
46 goto end;
47 }
48
49 while (time_remaining_ns > 0) {
50 ret = usleep(time_remaining_ns / (int64_t) NSEC_PER_USEC);
51 if (ret && errno != EINTR) {
52 perror("usleep");
53 goto end;
54 }
55
56 ret = lttng_clock_gettime(CLOCK_MONOTONIC, &t2);
57 if (ret) {
58 perror("clock_gettime");
59 goto end;
60 }
61
62 time_remaining_ns -= elapsed_time_ns(&t1, &t2);
63 }
64 end:
65 return ret;
66 }
67
68 int create_file(const char *path)
69 {
70 int ret;
71
72 if (!path) {
73 return -1;
74 }
75
76 ret = creat(path, S_IRWXU);
77 if (ret < 0) {
78 perror("creat");
79 return -1;
80 }
81
82 ret = close(ret);
83 if (ret < 0) {
84 perror("close");
85 return -1;
86 }
87
88 return 0;
89 }
90
91 int wait_on_file(const char *path)
92 {
93 int ret;
94 struct stat buf;
95
96 if (!path) {
97 return -1;
98 }
99
100 for (;;) {
101 ret = stat(path, &buf);
102 if (ret == -1 && errno == ENOENT) {
103 ret = poll(NULL, 0, 10); /* 10 ms delay */
104 /* Should return 0 everytime */
105 if (ret) {
106 if (ret < 0) {
107 perror("perror");
108 } else {
109 fprintf(stderr,
110 "poll return value is larger than zero\n");
111 }
112 return -1;
113 }
114 continue; /* retry */
115 }
116 if (ret) {
117 perror("stat");
118 return -1;
119 }
120 break; /* found */
121 }
122
123 return 0;
124 }
This page took 0.042739 seconds and 3 git commands to generate.