|
| 1 | +--TEST-- |
| 2 | +pcntl_fork() reseeds MT rand in child processes (GH-21351) |
| 3 | +--EXTENSIONS-- |
| 4 | +pcntl |
| 5 | +posix |
| 6 | +--FILE-- |
| 7 | +<?php |
| 8 | +/* |
| 9 | + * When MT rand is seeded before fork(), child processes must not inherit |
| 10 | + * the parent's MT state verbatim — each child should get a fresh seed |
| 11 | + * so that mt_rand() / array_rand() / shuffle() produce different sequences. |
| 12 | + */ |
| 13 | + |
| 14 | +// Ensure MT rand is seeded before forking |
| 15 | +mt_srand(42); |
| 16 | +mt_rand(); |
| 17 | + |
| 18 | +$tmpfile = tempnam(sys_get_temp_dir(), 'pcntl_mt_'); |
| 19 | + |
| 20 | +$children = 5; |
| 21 | +for ($i = 0; $i < $children; $i++) { |
| 22 | + $pid = pcntl_fork(); |
| 23 | + if ($pid == -1) { |
| 24 | + die("fork failed"); |
| 25 | + } else if ($pid == 0) { |
| 26 | + // Child: generate a value and write it to the shared temp file. |
| 27 | + // If reseeding works, children should not all produce the same value. |
| 28 | + $val = mt_rand(0, PHP_INT_MAX); |
| 29 | + file_put_contents($tmpfile, $val . "\n", FILE_APPEND | LOCK_EX); |
| 30 | + exit(0); |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +// Parent: wait for all children |
| 35 | +while (pcntl_wait($status) > 0); |
| 36 | + |
| 37 | +$lines = array_filter(array_map('trim', file($tmpfile))); |
| 38 | +$unique = array_unique($lines); |
| 39 | + |
| 40 | +// With 5 children and a 31-bit range, getting all identical values |
| 41 | +// from truly independent seeds is astronomically unlikely. |
| 42 | +if (count($unique) > 1) { |
| 43 | + echo "PASS: children produced different mt_rand values after fork\n"; |
| 44 | +} else { |
| 45 | + echo "FAIL: all children produced the same mt_rand value: " . $lines[0] . "\n"; |
| 46 | +} |
| 47 | + |
| 48 | +@unlink($tmpfile); |
| 49 | +?> |
| 50 | +--EXPECT-- |
| 51 | +PASS: children produced different mt_rand values after fork |
0 commit comments