1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) 2016 Cyril Hrubis <chrubis@suse.cz>
4 */
5
6 #include <stdio.h>
7 #include <unistd.h>
8 #include <stdlib.h>
9 #include <string.h>
10
print_help(void)11 static void print_help(void)
12 {
13 printf("Usage: tst_usleep interval[s|ms|us]\n\n");
14 printf(" If no unit is specified the interval is in seconds\n");
15 }
16
17 static struct unit {
18 const char *unit;
19 long mul;
20 } units[] = {
21 {"", 1000000},
22 {"s", 1000000},
23 {"ms", 1000},
24 {"us", 1},
25 };
26
27 static unsigned int units_len = sizeof(units) / sizeof(*units);
28
main(int argc,char * argv[])29 int main(int argc, char *argv[])
30 {
31 int opt;
32 long interval, secs = 0, usecs = 0;
33 unsigned int i;
34 char *end;
35
36 while ((opt = getopt(argc, argv, ":h")) != -1) {
37 switch (opt) {
38 case 'h':
39 print_help();
40 return 0;
41 default:
42 print_help();
43 return 1;
44 }
45 }
46
47 if (optind >= argc) {
48 fprintf(stderr, "ERROR: Expected interval argument\n\n");
49 print_help();
50 return 1;
51 }
52
53 interval = strtol(argv[optind], &end, 10);
54
55 if (argv[optind] == end) {
56 fprintf(stderr, "ERROR: Invalid interval '%s'\n\n",
57 argv[optind]);
58 print_help();
59 return 1;
60 }
61
62 for (i = 0; i < units_len; i++) {
63 if (!strcmp(units[i].unit, end))
64 break;
65 }
66
67 if (i >= units_len) {
68 fprintf(stderr, "ERROR: Invalid interval unit '%s'\n\n", end);
69 print_help();
70 return 1;
71 }
72
73 if (units[i].mul == 1000000)
74 secs = interval;
75
76 if (units[i].mul == 1000) {
77 secs = interval / 1000;
78 usecs = (interval % 1000) * 1000;
79 }
80
81 if (units[i].mul == 1) {
82 secs = interval / 1000000;
83 usecs = interval % 1000000;
84 }
85
86 if (secs)
87 sleep(secs);
88
89 if (usecs)
90 usleep(usecs);
91
92 return 0;
93 }
94