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