Init randomizer (was: Battleship source for Unix w/curses)
KW Heuer
kwh at bentley.UUCP
Thu Mar 27 01:10:56 AEST 1986
In article <4336 at dartvax.UUCP> dartvax!davidk (David C. Kovar) writes:
>>That's easy. Just insert a "srand(getpid());" somewhere in the beginning
>>of the program, before the first "rand" call.
>
>That'll still have the same problem. getpid() will return the same pid
>each time the same user runs it, thus you would get the same seed for
>rand each time. Try srand(time()); instead.
[0] You seem to be confusing getpid() with getuid(). On UNIX[tm], you
get a new process each time you run the program, so getpid() will return
a unique identifier. On some non-UNIX systems (with no fork/exec) you
may get the same ID each time.
[1] time() expects an argument. You need "time((long *)0)".
[2] time() returns a long. It must be declared as such.
[3] srand() expects an int. The result of time() must be cast.
(IMPORTANT: effects [2] and [3] do NOT cancel out if you ignore both!)
[4] I once ran the same program twice within one second (the resolution
of the UNIX clock) and got the same seed. Since then I've always used
both time() and getpid(), which seems to be a reasonable idea. (Messy?
Well, it's only done once per program!) (I wish srand(0) would do this
automatically!
Summary:
extern long time();
...
srand((int)time((long *)0) + getpid());
More information about the Comp.lang.c
mailing list