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