From: Tanaka Akira Date: 2005-01-03T02:05:52+09:00 Subject: [ruby-dev:25392] use /dev/urandom for srand if possible ふと、perl の srand が /dev/urandom を使うようになっていることに気がつ きました。 % grep urandom Changes* Changes5.005: Subject: seed srand from /dev/urandom when possible Changes5.6: Subject: seed srand from /dev/urandom when possible perl を見習って、ruby も使ってみるというのはどうでしょう? Index: random.c =================================================================== RCS file: /src/ruby/random.c,v retrieving revision 1.32 diff -u -p -r1.32 random.c --- random.c 15 Mar 2004 02:27:29 -0000 1.32 +++ random.c 2 Jan 2005 17:00:19 -0000 @@ -144,6 +144,11 @@ genrand_real() #include #endif #include +#include +#include +#ifdef HAVE_FCNTL_H +#include +#endif static int first = 1; @@ -167,9 +172,22 @@ random_seed() { static int n = 0; struct timeval tv; + unsigned long result; + int fd; + unsigned long buf; gettimeofday(&tv, 0); - return tv.tv_sec ^ tv.tv_usec ^ getpid() ^ n++; + result = tv.tv_sec ^ tv.tv_usec ^ getpid() ^ n++; + + result += (unsigned long)&result; + + if ((fd = open("/dev/urandom", O_RDONLY)) >= 0) { + read(fd, &buf, sizeof(buf)); + close(fd); + result ^= buf; + } + + return result; } /* なお、ローカル変数のアドレスを使うのも perl の真似です。 -- [田中 哲][たなか あきら][Tanaka Akira]