1 /*
2 * Copyright (c) 2016 Red Hat Inc.
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 * Author: Chunyu Hu <chuhu@redhat.com>
19 *
20 */
21
22 #include <stdio.h>
23 #include <unistd.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/time.h>
27
print_help(void)28 static void print_help(void)
29 {
30 printf("Usage: tst_random <value1> [value2]\n");
31 printf(" Generated random will be between value1 and value2.\n");
32 printf(" If only value1 is specified, value2 will treated as 0.\n");
33 }
34
get_seed(void)35 static int get_seed(void)
36 {
37 struct timeval tv;
38 gettimeofday(&tv, NULL);
39 return tv.tv_usec;
40 }
41
rand_range(long min,long max)42 static long rand_range(long min, long max)
43 {
44 return random() % (max - min + 1) + min;
45 }
46
main(int argc,char * argv[])47 int main(int argc, char *argv[])
48 {
49 int opt;
50 long min = 0, max = 0;
51 long rval = 0;
52 char *end;
53
54 while ((opt = getopt(argc, argv, ":h")) != -1) {
55 switch (opt) {
56 case 'h':
57 print_help();
58 return 0;
59 default:
60 print_help();
61 return 1;
62 }
63 }
64
65 if (argc != 2 && argc != 3) {
66 print_help();
67 return 1;
68 }
69
70 max = strtol(argv[1], &end, 10);
71 if (argv[1][0] == '\0' || *end != '\0') {
72 fprintf(stderr, "ERROR: Invalid range value1 '%s'\n\n",
73 argv[optind]);
74 print_help();
75 return 1;
76 }
77
78 if (argc == 3) {
79 min = strtol(argv[2], &end, 10);
80 if (argv[2][0] == '\0' || *end != '\0') {
81 fprintf(stderr, "ERROR: Invalid range value2 '%s'\n\n",
82 argv[optind+1]);
83 print_help();
84 return 1;
85 }
86 }
87
88 srandom(get_seed());
89 rval = (min > max) ? rand_range(max, min) : rand_range(min, max);
90 printf("%ld\n", rval);
91
92 return 0;
93 }
94