返回 DeepSeek-Reasonix
kill_other_test.go
根目录 / internal / proc / kill_other_test.go
1 //go:build !windows
2
3 package proc
4
5 import (
6 "bufio"
7 "errors"
8 "os/exec"
9 "strconv"
10 "strings"
11 "syscall"
12 "testing"
13 "time"
14 )
15
16 func TestSetProcessGroupKillDetachesSession(t *testing.T) {
17 cmd := exec.Command("true")
18 SetProcessGroupKill(cmd)
19 if cmd.SysProcAttr == nil {
20 t.Fatal("SysProcAttr is nil")
21 }
22 if !cmd.SysProcAttr.Setsid {
23 t.Fatal("SetProcessGroupKill should detach the child into a new session")
24 }
25 }
26
27 func TestKillTreeTerminatesChild(t *testing.T) {
28 cmd := exec.Command("sleep", "30")
29 if err := cmd.Start(); err != nil {
30 t.Fatalf("Start: %v", err)
31 }
32
33 KillTree(cmd)
34
35 done := make(chan error, 1)
36 go func() { done <- cmd.Wait() }()
37 select {
38 case <-done:
39 case <-time.After(5 * time.Second):
40 t.Fatal("cmd.Wait blocked after KillTree")
41 }
42 }
43
44 func TestKillTrackedTerminatesChild(t *testing.T) {
45 cmd := exec.Command("sleep", "30")
46 job, err := StartTracked(cmd)
47 if err != nil {
48 t.Fatalf("StartTracked: %v", err)
49 }
50 if job != 0 {
51 t.Fatalf("StartTracked job = %d off Windows; want 0", job)
52 }
53
54 KillTracked(cmd, job)
55
56 done := make(chan error, 1)
57 go func() { done <- cmd.Wait() }()
58 select {
59 case <-done:
60 case <-time.After(5 * time.Second):
61 t.Fatal("cmd.Wait blocked after KillTracked")
62 }
63 }
64
65 // A launcher (sh) that backgrounds a grandchild (sleep) and stays alive: with
66 // the child in its own process group, KillTracked's negative-pid kill must reap
67 // the grandchild too, not just sh.
68 func TestKillTrackedReapsProcessGroupGrandchild(t *testing.T) {
69 cmd := exec.Command("sh", "-c", "sleep 60 & echo $!; wait")
70 stdout, err := cmd.StdoutPipe()
71 if err != nil {
72 t.Fatalf("StdoutPipe: %v", err)
73 }
74 if _, err := StartTracked(cmd); err != nil {
75 t.Fatalf("StartTracked: %v", err)
76 }
77
78 line, err := bufio.NewReader(stdout).ReadString('\n')
79 if err != nil {
80 t.Fatalf("read grandchild pid: %v", err)
81 }
82 gcPid, err := strconv.Atoi(strings.TrimSpace(line))
83 if err != nil || gcPid <= 0 {
84 t.Fatalf("bad grandchild pid %q: %v", line, err)
85 }
86 if syscall.Kill(gcPid, 0) != nil {
87 t.Fatalf("grandchild %d not alive before kill", gcPid)
88 }
89
90 KillTracked(cmd, 0)
91 _ = cmd.Wait()
92
93 deadline := time.Now().Add(5 * time.Second)
94 for !errors.Is(syscall.Kill(gcPid, 0), syscall.ESRCH) {
95 if time.Now().After(deadline) {
96 t.Fatalf("grandchild %d survived KillTracked — process group not reaped", gcPid)
97 }
98 time.Sleep(20 * time.Millisecond)
99 }
100 }
101
101 lines GO