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