2 * collectd - src/sn_random.c
3 * Copyright (C) 2008 Florian octo Forster
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; only version 2 of the License is applicable.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 * Florian octo Forster <octo at verplant.org>
22 #define _ISOC99_SOURCE
23 #define _POSIX_C_SOURCE 200112L
27 #include <sys/types.h>
35 #include "sn_random.h"
37 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
38 static unsigned int seed;
39 static int have_init = 0;
41 static int read_dev_random (void *buffer, size_t buffer_size)
46 char *buffer_position;
49 fd = open ("/dev/random", O_RDONLY);
56 buffer_position = (char *) buffer;
57 yet_to_read = buffer_size;
59 while (yet_to_read > 0)
61 status = read (fd, (void *) buffer_position, yet_to_read);
67 fprintf (stderr, "read_dev_random: read failed.\n");
71 buffer_position += status;
72 yet_to_read -= (size_t) status;
80 } /* int read_dev_random */
82 static void do_init (void)
86 status = read_dev_random (&seed, sizeof (seed));
95 pthread_mutex_lock (&lock);
100 ret = rand_r (&seed);
102 pthread_mutex_unlock (&lock);
105 } /* int sn_random */
107 int sn_true_random (void)
112 status = read_dev_random (&ret, sizeof (ret));
114 return (sn_random ());
117 } /* int sn_true_random */
119 int sn_bounded_random (int min, int max)
133 range = 1 + max - min;
134 rand = min + (int) (((double) range)
135 * (((double) sn_random ()) / (((double) RAND_MAX) + 1.0)));
137 assert (rand >= min);
138 assert (rand <= max);
141 } /* int sn_bounded_random */
143 /* vim: set shiftwidth=2 softtabstop=2 : */