• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2016 Cyril Hrubis <chrubis@suse.cz>
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License as
6  * published by the Free Software Foundation; either version 2 of
7  * the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it would be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write the Free Software Foundation,
16  * Inc.,  51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17  */
18 
19 #include <stdio.h>
20 #include <unistd.h>
21 #include <stdlib.h>
22 #include <string.h>
23 
print_help(void)24 static void print_help(void)
25 {
26 	printf("Usage: tst_usleep interval[s|ms|us]\n\n");
27 	printf("       If no unit is specified the interval is in seconds\n");
28 }
29 
30 static struct unit {
31 	const char *unit;
32 	long mul;
33 } units[] = {
34 	{"",   1000000},
35 	{"s",  1000000},
36 	{"ms", 1000},
37 	{"us", 1},
38 };
39 
40 static unsigned int units_len = sizeof(units) / sizeof(*units);
41 
main(int argc,char * argv[])42 int main(int argc, char *argv[])
43 {
44 	int opt;
45 	long interval, secs = 0, usecs = 0;
46 	unsigned int i;
47 	char *end;
48 
49 	while ((opt = getopt(argc, argv, ":h")) != -1) {
50 		switch (opt) {
51 		case 'h':
52 			print_help();
53 			return 0;
54 		default:
55 			print_help();
56 			return 1;
57 		}
58 	}
59 
60 	if (optind >= argc) {
61 		fprintf(stderr, "ERROR: Expected interval argument\n\n");
62 		print_help();
63 		return 1;
64 	}
65 
66 	interval = strtol(argv[optind], &end, 10);
67 
68 	if (argv[optind] == end) {
69 		fprintf(stderr, "ERROR: Invalid interval '%s'\n\n",
70 		        argv[optind]);
71 		print_help();
72 		return 1;
73 	}
74 
75 	for (i = 0; i < units_len; i++) {
76 		if (!strcmp(units[i].unit, end))
77 			break;
78 	}
79 
80 	if (i >= units_len) {
81 		fprintf(stderr, "ERROR: Invalid interval unit '%s'\n\n", end);
82 		print_help();
83 		return 1;
84 	}
85 
86 	if (units[i].mul == 1000000)
87 		secs = interval;
88 
89 	if (units[i].mul == 1000) {
90 		secs = interval / 1000;
91 		usecs = (interval % 1000) * 1000;
92 	}
93 
94 	if (units[i].mul == 1) {
95 		secs = interval / 1000000;
96 		usecs = interval % 1000000;
97 	}
98 
99 	if (secs)
100 		sleep(secs);
101 
102 	if (usecs)
103 		usleep(usecs);
104 
105 	return 0;
106 }
107