view TaskManager/kernel/ppe/Random.cc @ 298:768452fab95e draft

from EUC to UTF-8
author Shinji KONO <kono@ie.u-ryukyu.ac.jp>
date Sun, 07 Jun 2009 15:17:41 +0900
parents 56314060907f
children 4748fd7dcd89
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();
}