1 /*
2 rnd.c
3
4 Generate random numbers
5 */
6
7 #include <stdarg.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <unistd.h>
12
13 static char *progname;
14
15 static void fatal(char *fmt, ...);
16 static void usage(void);
17
main(int argc,char * argv[])18 int main(int argc, char *argv[])
19 {
20 int c, i, count;
21 unsigned long n, v, high, modulus;
22 unsigned seed;
23 char *check;
24 char *c_arg, *m_arg, *s_arg;
25
26 (progname=strrchr(argv[0],'/')) ? progname++ : (progname=argv[0]);
27
28 c_arg= m_arg= s_arg= NULL;
29 while (c= getopt(argc, argv, "?c:m:s:"), c != -1)
30 {
31 switch(c)
32 {
33 case 'c': c_arg= optarg; break;
34 case 'm': m_arg= optarg; break;
35 case 's': s_arg= optarg; break;
36 default:
37 fatal("getopt failed: '%c'", c);
38 }
39 }
40 if (optind != argc)
41 usage();
42 if (c_arg)
43 {
44 count= strtol(c_arg, &check, 0);
45 if (check[0] != '\0')
46 fatal("bad count '%s'", c_arg);
47 }
48 else
49 count= 1;
50 if (m_arg)
51 {
52 modulus= strtoul(m_arg, &check, 0);
53 if (check[0] != '\0' || modulus == 0)
54 fatal("bad modulus '%s'", m_arg);
55 n= 0x80000000UL / modulus;
56 if (n == 0)
57 fatal("bad modulus %lu (too big)", modulus);
58 high= n * modulus;
59 }
60 else
61 modulus= high= 0x80000000UL;
62 if (s_arg)
63 {
64 seed= strtol(s_arg, &check, 0);
65 if (check[0] != '\0')
66 fatal("bad seed '%s'", s_arg);
67 srandom(seed);
68 }
69
70 for (i= 0; i<count; i++)
71 {
72 do
73 {
74 v= random();
75 } while (v > high);
76
77 printf("%lu\n", v % modulus);
78 }
79 }
80
fatal(char * fmt,...)81 static void fatal(char *fmt, ...)
82 {
83 va_list ap;
84
85 fprintf(stderr, "%s: ", progname);
86 va_start(ap, fmt);
87 vfprintf(stderr, fmt, ap);
88 va_end(ap);
89 fprintf(stderr, "\n");
90 exit(1);
91 }
92
usage(void)93 static void usage(void)
94 {
95 fprintf(stderr, "Usage: rnd [-c <count>] [-m <modulus>] [-s <seed>]\n");
96 exit(1);
97 }
98