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 #ifndef _ISOC99_SOURCE
23 # define _ISOC99_SOURCE
25 #ifndef _POSIX_C_SOURCE
26 # define _POSIX_C_SOURCE 200112L
31 #include <sys/types.h>
39 #include "sn_random.h"
41 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
42 static unsigned int seed;
43 static int have_init = 0;
45 static int read_dev_random (void *buffer, size_t buffer_size)
50 char *buffer_position;
53 fd = open ("/dev/random", O_RDONLY);
60 buffer_position = (char *) buffer;
61 yet_to_read = buffer_size;
63 while (yet_to_read > 0)
65 status = read (fd, (void *) buffer_position, yet_to_read);
71 fprintf (stderr, "read_dev_random: read failed.\n");
75 buffer_position += status;
76 yet_to_read -= (size_t) status;
84 } /* int read_dev_random */
86 static void do_init (void)
90 status = read_dev_random (&seed, sizeof (seed));
99 pthread_mutex_lock (&lock);
104 ret = rand_r (&seed);
106 pthread_mutex_unlock (&lock);
109 } /* int sn_random */
111 int sn_true_random (void)
116 status = read_dev_random (&ret, sizeof (ret));
118 return (sn_random ());
121 } /* int sn_true_random */
123 int sn_bounded_random (int min, int max)
137 range = 1 + max - min;
138 rand = min + (int) (((double) range)
139 * (((double) sn_random ()) / (((double) RAND_MAX) + 1.0)));
141 assert (rand >= min);
142 assert (rand <= max);
145 } /* int sn_bounded_random */
147 /* vim: set shiftwidth=2 softtabstop=2 : */