Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: problems with RANDOM in subshells



Clint Adams wrote:
>Should the random-seeding behavior be changed for subshells?

No.  We define $RANDOM to be a PRNG; zshparam(1) speaks of seeding it
(by writing to $RANDOM).  Opening a subshell should not interfere with
the PRNG sequence, which one might be relying on to be reproducible.
That is, we should maintain this useful behaviour:

	% RANDOM=1234; echo $RANDOM; echo $RANDOM
	8718
	31363
	% RANDOM=1234; echo $RANDOM; (echo $RANDOM)
	8718
	31363
	% RANDOM=1234; (echo $RANDOM; echo $RANDOM)
	8718
	31363
	% (RANDOM=1234; echo $RANDOM; echo $RANDOM)
	8718
	31363

Where one requires unpredictability rather than reproducibility, it is
well known (see Knoth vol. 2, et al) that one must take extra steps.
For example, in an application that forks off subshells and needs a new
random number in each subshell, one must at minimum step the PRNG between
subshells.  (Either each subshell uses the next random number generated
by the main program, or each runs the PRNG itself, duplicating a random
number that the main program generates and throws away.)  To get wildly
different random *sequences* in each subshell, rather than just a single
random number, one can kink the PRNG sequence by doing "RANDOM=$RANDOM"
between subshells.

(In my interactive zsh setup, I step the PRNG with ": $RANDOM" in precmd.
This largely solves the problem for interactive use of $RANDOM --
subshells started at different prompts get different (albeit overlapping)
$RANDOM sequences.)

For zsh-workers:

It may be useful to add, separately from the PRNG, an entropy collection
module.  This would generate moderate-quality *unpredictable* numbers
on demand; unlike the $RANDOM PRNG its output would be irreproducible.
The shell is probably a good place to put an entropy collector; on systems
like Linux that have /dev/random we can just use the kernel device,
but on other systems the shell is still in a position to see a lot of
unpredictable timing data, so we can make randomness reliably available
to shell scripts on all Unices.  (Does Perl have such a module yet?)

-zefram



Messages sorted by: Reverse Date, Date, Thread, Author