view TaskManager/kernel/ppe/Random.cc @ 247:0098b5ff0d11

change example
author aaa
date Mon, 01 Jun 2009 19:33:09 +0900
parents 2b114977852d
children 4435c9990988
line wrap: on
line source

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include "Random.h"

/**
 * /dev/urandom, random から取得した値を seed として使う
 */
Random::Random(void)
{
    reset();
}

/**
 * 引数で seed を指定する
 */
Random::Random(unsigned int seed)
{
    srandom(seed);
}

void
Random::reset(void)
{
    FILE *fp;
    unsigned int seed;
    struct timeval tv;

    fp = fopen("/dev/urandom", "r");
    if (!fp) fp = fopen("/dev/random", "r");

    if (fp) {
	int res = fread(&seed, sizeof(unsigned int), 1, fp);
	if (res != sizeof(unsigned int)) {
	    fclose(fp);
	    fp = NULL;
	}
    }

    if (!fp) {
	gettimeofday(&tv, NULL);
	seed = (tv.tv_sec ^ tv.tv_usec);
    } else {
	fclose(fp);
    }

    srandom(seed);
}

int
Random::getData(void)
{
    return random();
}