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