sessiond: kernel triggers: add infrastructure to create event notifiers
[lttng-tools.git] / tests / utils / utils.c
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
b2047add 8#include <assert.h>
389fbf04 9#include <common/compat/time.h>
395d6b02 10#include <common/time.h>
b2047add
FD
11#include <fcntl.h>
12#include <poll.h>
13#include <stdbool.h>
14#include <stdint.h>
15#include <stdio.h>
16#include <stdlib.h>
17#include <sys/stat.h>
18#include <sys/types.h>
19#include <unistd.h>
20
edf4b93e
MJ
21#include <common/compat/errno.h>
22
b2047add 23#include "utils.h"
0458ed8c 24
0458ed8c
JG
25static inline
26int64_t elapsed_time_ns(struct timespec *t1, struct timespec *t2)
27{
28 struct timespec delta;
29
30 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
37int 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
389fbf04 43 ret = lttng_clock_gettime(CLOCK_MONOTONIC, &t1);
0458ed8c
JG
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
838193da 57 ret = lttng_clock_gettime(CLOCK_MONOTONIC, &t2);
0458ed8c
JG
58 if (ret) {
59 perror("clock_gettime");
60 goto end;
61 }
62
63 time_remaining_ns -= elapsed_time_ns(&t1, &t2);
64 }
65end:
66 return ret;
67}
b2047add
FD
68
69int 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
92int 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.052781 seconds and 4 git commands to generate.