| 1 | //go:build linux |
| 2 | |
| 3 | package engine |
| 4 | |
| 5 | import ( |
| 6 | "fmt" |
| 7 | "os" |
| 8 | "os/exec" |
| 9 | "strings" |
| 10 | "testing" |
| 11 | ) |
| 12 | |
| 13 | func procStatState(t *testing.T, pid int) (byte, error) { |
| 14 | t.Helper() |
| 15 | raw, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid)) |
| 16 | if err != nil { |
| 17 | return 0, err |
| 18 | } |
| 19 | // Format is: "<pid> (<comm>) <state> ..."; comm may contain spaces or ')'. |
| 20 | idx := strings.LastIndexByte(string(raw), ')') |
| 21 | if idx < 0 || idx+2 >= len(raw) { |
| 22 | return 0, fmt.Errorf("unexpected /proc/%d/stat format: %q", pid, raw) |
| 23 | } |
| 24 | return raw[idx+2], nil |
| 25 | } |
| 26 | |
| 27 | // TestWaitChildNoReapKeepsZombiePinned verifies directly against Linux /proc |
| 28 | // that waitChildNoReap observes child exit while leaving the process as an |
| 29 | // unreaped zombie ('Z'), pinning its PID/PGID until cmd.Wait() runs. |
| 30 | func TestWaitChildNoReapKeepsZombiePinned(t *testing.T) { |
| 31 | cmd := exec.Command("/bin/sh", "-c", "exit 0") |
| 32 | setProcessGroup(cmd) |
| 33 | if err := cmd.Start(); err != nil { |
| 34 | t.Fatalf("start child: %v", err) |
| 35 | } |
| 36 | pid := cmd.Process.Pid |
| 37 | |
| 38 | if err := waitChildNoReap(pid); err != nil { |
| 39 | _ = cmd.Wait() |
| 40 | t.Fatalf("waitChildNoReap(%d): %v", pid, err) |
| 41 | } |
| 42 | |
| 43 | state, err := procStatState(t, pid) |
| 44 | if err != nil { |
| 45 | _ = cmd.Wait() |
| 46 | t.Fatalf("child pid %d vanished before cmd.Wait(): %v", pid, err) |
| 47 | } |
| 48 | if state != 'Z' { |
| 49 | _ = cmd.Wait() |
| 50 | t.Fatalf("child pid %d state = %q after waitChildNoReap, want 'Z' (unreaped zombie)", pid, state) |
| 51 | } |
| 52 | |
| 53 | if err := cmd.Wait(); err != nil { |
| 54 | t.Fatalf("cmd.Wait() after waitChildNoReap: %v", err) |
| 55 | } |
| 56 | if _, err := os.Stat(fmt.Sprintf("/proc/%d/stat", pid)); err == nil { |
| 57 | t.Fatalf("child pid %d still exists in /proc after cmd.Wait() reap", pid) |
| 58 | } |
| 59 | } |
| 60 |