|
| 1 | +package reaper |
| 2 | + |
| 3 | +import ( |
| 4 | + "syscall" |
| 5 | + "testing" |
| 6 | + "time" |
| 7 | +) |
| 8 | + |
| 9 | +func exit(code int) syscall.WaitStatus { return syscall.WaitStatus(code << 8) } |
| 10 | + |
| 11 | +// TestWaitDropsStalePIDReuse ensures a buffered status left by an earlier child |
| 12 | +// is not handed to a new child that reused the same pid: Wait must ignore the |
| 13 | +// stale entry, install a fresh waiter, and route the new child's real exit |
| 14 | +// (R-SINIT5). |
| 15 | +func TestWaitDropsStalePIDReuse(t *testing.T) { |
| 16 | + r := NewRegistry() |
| 17 | + // An orphan exited earlier with pid 100 and its status was buffered (no waiter). |
| 18 | + r.Deliver(100, exit(7)) |
| 19 | + // Age it so it predates the reused pid's registration. |
| 20 | + r.mu.Lock() |
| 21 | + r.pending[100] = pending{ws: exit(7), at: time.Now().Add(-5 * time.Second)} |
| 22 | + r.mu.Unlock() |
| 23 | + |
| 24 | + ch := r.Wait(100) // a new child reused pid 100 and registers interest |
| 25 | + select { |
| 26 | + case ws := <-ch: |
| 27 | + t.Fatalf("Wait returned stale status (exit %d) for a reused pid; must wait for the new child", ws.ExitStatus()) |
| 28 | + default: |
| 29 | + } |
| 30 | + |
| 31 | + r.Deliver(100, exit(0)) // the new child's real exit |
| 32 | + select { |
| 33 | + case ws := <-ch: |
| 34 | + if ws.ExitStatus() != 0 { |
| 35 | + t.Errorf("routed exit %d, want 0 (the new child)", ws.ExitStatus()) |
| 36 | + } |
| 37 | + default: |
| 38 | + t.Fatal("the new child's status did not route to the waiter") |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +// TestWaitReturnsFreshBufferedStatus keeps the legitimate register-vs-exit race |
| 43 | +// working: a status buffered just before Wait is returned immediately. |
| 44 | +func TestWaitReturnsFreshBufferedStatus(t *testing.T) { |
| 45 | + r := NewRegistry() |
| 46 | + r.Deliver(200, exit(3)) |
| 47 | + select { |
| 48 | + case ws := <-r.Wait(200): |
| 49 | + if ws.ExitStatus() != 3 { |
| 50 | + t.Errorf("got exit %d, want 3", ws.ExitStatus()) |
| 51 | + } |
| 52 | + default: |
| 53 | + t.Fatal("a freshly buffered status should be returned immediately") |
| 54 | + } |
| 55 | +} |
0 commit comments