libc, libutil: remove compat hacks
[minix.git] / commands / swifi / rnd.c
blob4412e2ff24f43e0fa9d4078fa409181320aceca9
1 /*
2 rnd.c
4 Generate random numbers
5 */
7 #define _POSIX_SOURCE
9 #include <stdarg.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <unistd.h>
15 static char *progname;
17 static void fatal(char *fmt, ...);
18 static void usage(void);
20 int main(int argc, char *argv[])
22 int c, i, count;
23 unsigned long n, v, high, modulus;
24 unsigned seed;
25 char *check;
26 char *c_arg, *m_arg, *s_arg;
28 (progname=strrchr(argv[0],'/')) ? progname++ : (progname=argv[0]);
30 c_arg= m_arg= s_arg= NULL;
31 while (c= getopt(argc, argv, "?c:m:s:"), c != -1)
33 switch(c)
35 case 'c': c_arg= optarg; break;
36 case 'm': m_arg= optarg; break;
37 case 's': s_arg= optarg; break;
38 default:
39 fatal("getopt failed: '%c'", c);
42 if (optind != argc)
43 usage();
44 if (c_arg)
46 count= strtol(c_arg, &check, 0);
47 if (check[0] != '\0')
48 fatal("bad count '%s'", c_arg);
50 else
51 count= 1;
52 if (m_arg)
54 modulus= strtoul(m_arg, &check, 0);
55 if (check[0] != '\0' || modulus == 0)
56 fatal("bad modulus '%s'", m_arg);
57 n= 0x80000000UL / modulus;
58 if (n == 0)
59 fatal("bad modulus %lu (too big)", modulus);
60 high= n * modulus;
62 else
63 modulus= high= 0x80000000UL;
64 if (s_arg)
66 seed= strtol(s_arg, &check, 0);
67 if (check[0] != '\0')
68 fatal("bad seed '%s'", s_arg);
69 srandom(seed);
72 for (i= 0; i<count; i++)
76 v= random();
77 } while (v > high);
79 printf("%lu\n", v % modulus);
83 static void fatal(char *fmt, ...)
85 va_list ap;
87 fprintf(stderr, "%s: ", progname);
88 va_start(ap, fmt);
89 vfprintf(stderr, fmt, ap);
90 va_end(ap);
91 fprintf(stderr, "\n");
92 exit(1);
95 static void usage(void)
97 fprintf(stderr, "Usage: rnd [-c <count>] [-m <modulus>] [-s <seed>]\n");
98 exit(1);