关于/dev/random和/dev/urandom求随机数

软件和网站开发以及相关技术探讨
回复
iamcook84
帖子: 41
注册时间: 2013-08-29 9:27

关于/dev/random和/dev/urandom求随机数

#1

帖子 iamcook84 » 2016-03-28 16:16

代码: 全选

#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次。为何?
头像
astolia
论坛版主
帖子: 6386
注册时间: 2008-09-18 13:11

Re: 关于/dev/random和/dev/urandom求随机数

#2

帖子 astolia » 2016-05-02 15:03

你先搞清楚/dev/random和/dev/urandom的区别,自然就知道是怎么回事了
rosynirvana
帖子: 893
注册时间: 2011-02-14 17:46

Re: 关于/dev/random和/dev/urandom求随机数

#3

帖子 rosynirvana » 2016-05-02 18:08

man random
回复