1
0
mirror of https://git.FreeBSD.org/src.git synced 2024-12-01 08:27:59 +00:00

Added Posix rand_r function.

This commit is contained in:
Wes Peters 1999-05-24 23:30:14 +00:00
parent c9091105f3
commit b7edcd43b5
Notes: svn2git 2020-12-20 02:59:44 +00:00
svn path=/head/; revision=47474
2 changed files with 74 additions and 5 deletions

View File

@ -35,12 +35,13 @@
.\"
.\" @(#)rand.3 8.1 (Berkeley) 6/4/93
.\"
.Dd June 4, 1993
.Dd May 25, 1999
.Dt RAND 3
.Os
.Sh NAME
.Nm rand ,
.Nm srand
.Nm srand ,
.Nm rand_r
.Nd bad random number generator
.Sh SYNOPSIS
.Fd #include <stdlib.h>
@ -48,6 +49,8 @@
.Fn srand "unsigned seed"
.Ft int
.Fn rand void
.Ft int
.Fn rand_r "unsigned *ctx"
.Sh DESCRIPTION
.Bf -symbolic
These interfaces are obsoleted by random(3).
@ -63,15 +66,26 @@ of 0 to
.Pp
The
.Fn srand
function sets its argument as the seed for a new sequence of
function sets its argument
.Fa seed
as the seed for a new sequence of
pseudo-random numbers to be returned by
.Fn rand .
These sequences are repeatable by calling
.Fn srand
with the same seed value.
.Pp
If no seed value is provided, the functions are automatically
If no
.Fa seed
value is provided, the functions are automatically
seeded with a value of 1.
.Pp
.Fn rand_r
provides the same functionality as
.Fn rand .
A pointer to the context value
.Fa ctx
must be supplied by the caller.
.Sh SEE ALSO
.Xr random 3
.Sh STANDARDS
@ -82,3 +96,7 @@ and
functions
conform to
.St -ansiC .
.Pp
The
.Fn rand_r
function is as proposed in the POSIX.4a Draft #6 document.

View File

@ -29,6 +29,8 @@
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* Posix rand_r function added May 1999 by Wes Peters <wes@softweyr.com>.
*/
#if defined(LIBC_SCCS) && !defined(lint)
@ -38,12 +40,32 @@ static char sccsid[] = "@(#)rand.c 8.1 (Berkeley) 6/14/93";
#include <sys/types.h>
#include <stdlib.h>
#ifdef TEST
#include <stdio.h>
#endif /* TEST */
static int
do_rand(unsigned long *ctx)
{
return ((*ctx = *ctx * 1103515245 + 12345) % ((u_long)RAND_MAX + 1));
}
int
rand_r(unsigned int *ctx)
{
u_long val = (u_long) *ctx;
*ctx = do_rand(&val);
return (int) *ctx;
}
static u_long next = 1;
int
rand()
{
return ((next = next * 1103515245 + 12345) % ((u_long)RAND_MAX + 1));
return do_rand(&next);
}
void
@ -52,3 +74,32 @@ u_int seed;
{
next = seed;
}
#ifdef TEST
main()
{
int i;
unsigned myseed;
printf("seeding rand with 0x19610910: \n");
srand(0x19610910);
printf("generating three pseudo-random numbers:\n");
for (i = 0; i < 3; i++)
{
printf("next random number = %d\n", rand());
}
printf("generating the same sequence with rand_r:\n");
myseed = 0x19610910;
for (i = 0; i < 3; i++)
{
printf("next random number = %d\n", rand_r(&myseed));
}
return 0;
}
#endif /* TEST */