On Sat, Dec 10, 2005 at 01:25:22AM +0000, Stephen Gran wrote: > So, with this test: > > #!/usr/bin/perl > > use POSIX ":sys_wait_h"; > > my $count = 0; > for (0.. 99) { > &do_test(1); > } > > print "Test (rand) passed $count % of the time\n"; > > $count = 0; > for (0.. 99) { > &do_test(0); > } > > print "Test (fixed) passed $count % of the time\n"; > > sub do_test { > my $try = shift; > pipe(RDR,WTR) or die $!; > my $pid = fork; > die "fork: $!" if !defined $pid; > if ($pid == 0) { > my $rand_child; > if ($try == 1) { > $rand_child = rand; > } else { > $rand_child = 2; > } > close RDR; > print WTR $rand_child, "\n"; > close WTR; > exit 0; > } elsif ($pid > 0) { > my $rand_parent; > if ($try == 1) { > $rand_parent = rand; > } else { > $rand_parent = 1; > } > close WTR; > chomp(my $rand_child = <RDR>); > close RDR; > my $kid; > do { > $kid = waitpid($pid, 0); > } until $kid > 0; > $count++ if ($rand_child ne $rand_parent); > } else { > die "Can't fork: $!\n"; > } > } > > I get: > Test (rand) passed 1 % of the time > Test (fixed) passed 100 % of the time > > This is because the parent and the child get the same value for rand() > almost every time (although oddly, the first time almost always succeeds > in getting different values, so the original test passed most of the > time).
That should have been your clue. The first time you call rand(), perl opens /dev/urandom and collects some truly random data to seed the PRNG with, if you haven't already called srand. So, the first iteration of your test forks, calls rand in the child (seeds with a fresh value), calls rand in the parent (seeds again), and gets two different values. The second iteration... has already been seeded, so they produce the same number. The fork.t script spawns a new instance of perl each time, avoiding such problems. I have a copy of fork.t, hacked to run outside the perl source tree, which I've tried running a whole load of times on mips and anything else to hand... it hasn't failed yet. My best guess is that /dev/urandom on the buildd isn't working right, but it's sheer guesswork since I can't actually look at the thing. -- .''`. ** Debian GNU/Linux ** | Andrew Suffield : :' : http://www.debian.org/ | `. `' | `- -><- |
signature.asc
Description: Digital signature