// Copyright (c) Tailscale Inc & contributors // SPDX-License-Identifier: BSD-3-Clause //go:build linux && !android package tailssh import ( "os/exec" "syscall" "testing" "time" ) // TestZombieWaitStatus checks that zombieWaitStatus reads exited and // killed children's wait statuses without reaping them. func TestZombieWaitStatus(t *testing.T) { for _, tc := range []struct { name string script string wantExit int // if !wantSignal wantSignal bool // killed by SIGKILL }{ {name: "exit", script: "exit 7", wantExit: 7}, {name: "killed", script: "kill -KILL $$", wantSignal: true}, } { t.Run(tc.name, func(t *testing.T) { cmd := exec.Command("/bin/sh", "-c", tc.script) if err := cmd.Start(); err != nil { t.Fatal(err) } pid := cmd.Process.Pid if ws, ok := zombieWaitStatus(pid); ok && !ws.Exited() && !ws.Signaled() { t.Fatalf("running child status = %#x", ws) } deadline := time.Now().Add(10 * time.Second) for { ws, ok := zombieWaitStatus(pid) if ok { if tc.wantSignal { if !ws.Signaled() || ws.Signal() != syscall.SIGKILL { t.Errorf("status = %#x; want killed by SIGKILL", ws) } } else if !ws.Exited() || ws.ExitStatus() != tc.wantExit { t.Errorf("status = %#x; want exit %d", ws, tc.wantExit) } break } if time.Now().After(deadline) { t.Fatal("child did not exit") } time.Sleep(10 * time.Millisecond) } // The child must still be unreaped, so Wait gets its status. err := cmd.Wait() if tc.wantSignal { if cmd.ProcessState.Sys().(syscall.WaitStatus).Signal() != syscall.SIGKILL { t.Errorf("Wait = %v; want SIGKILL", err) } } else if cmd.ProcessState.ExitCode() != tc.wantExit { t.Errorf("Wait = %v; want exit %d", err, tc.wantExit) } }) } }