代码: 全选
#include <sys/time.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <inttypes.h>
#include <stdint.h>
#include <limits.h>
unsigned long static openwrong=0, readwrong=0,goodnum=0,overflow=0;
unsigned long myrandom()
{
unsigned long data;
struct timeval ti;
gettimeofday(&ti,NULL);
unsigned long seed=ti.tv_usec;
int fd=open("/dev/random",O_RDONLY);//1022次以后出问题,fd<=0;
if(fd<0 )
{
srandom(seed);
data=random();
openwrong++;
}
else if (read(fd,&data,sizeof(data))<=0)
{
srandom(seed);
data=random();
readwrong++;
}
else if(data>SSIZE_MAX)//有可能溢出
{
overflow++;
data=data%SSIZE_MAX;
}
else goodnum++;
return data;
}
int main(int argc, char **argv)
{
unsigned long i,num=1050;//1022次以后出问题
for(i=1;i<num;i++)
printf("myrandom%ld=%ld\n",i, myrandom());
printf("openwrong=%ld,readwrong=%ld,overflow=%ld,goodnum=%ld\n",openwrong,readwrong,overflow,goodnum);
return 0;
}
//看到一本老外写的书。上面写了利用 /dev/random 和/dev/urandom 计算伪随机数较为可信。
//可是我试了,只可利用1021次。为何?