1// Copyright 2020 The Go Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style 3// license that can be found in the LICENSE file. 4 5//go:build unix 6 7package os_test 8 9import ( 10 "errors" 11 "internal/testenv" 12 "math" 13 . "os" 14 "runtime" 15 "syscall" 16 "testing" 17) 18 19func TestErrProcessDone(t *testing.T) { 20 testenv.MustHaveGoBuild(t) 21 t.Parallel() 22 23 p, err := StartProcess(testenv.GoToolPath(t), []string{"go"}, &ProcAttr{}) 24 if err != nil { 25 t.Fatalf("starting test process: %v", err) 26 } 27 p.Wait() 28 if got := p.Signal(Kill); got != ErrProcessDone { 29 t.Errorf("got %v want %v", got, ErrProcessDone) 30 } 31} 32 33// Lookup of a process that does not exist at time of lookup. 34func TestProcessAlreadyDone(t *testing.T) { 35 // Theoretically MaxInt32 is a valid PID, but the chance of it actually 36 // being used is extremely unlikely. 37 pid := math.MaxInt32 38 if runtime.GOOS == "solaris" || runtime.GOOS == "illumos" { 39 // Solaris/Illumos have a lower limit, above which wait returns 40 // EINVAL (see waitid in usr/src/uts/common/os/exit.c in 41 // illumos). This is configurable via sysconf(_SC_MAXPID), but 42 // we'll just take the default. 43 pid = 30000 - 1 44 } 45 46 p, err := FindProcess(pid) 47 if err != nil { 48 t.Fatalf("FindProcess(math.MaxInt32) got err %v, want nil", err) 49 } 50 51 if ps, err := p.Wait(); !errors.Is(err, syscall.ECHILD) { 52 t.Errorf("Wait() got err %v (ps %+v), want %v", err, ps, syscall.ECHILD) 53 } 54 55 if err := p.Release(); err != nil { 56 t.Errorf("Release() got err %v, want nil", err) 57 } 58} 59 60func TestUNIXProcessAlive(t *testing.T) { 61 testenv.MustHaveGoBuild(t) 62 t.Parallel() 63 64 p, err := StartProcess(testenv.GoToolPath(t), []string{"sleep", "1"}, &ProcAttr{}) 65 if err != nil { 66 t.Skipf("starting test process: %v", err) 67 } 68 defer p.Kill() 69 70 proc, err := FindProcess(p.Pid) 71 if err != nil { 72 t.Errorf("OS reported error for running process: %v", err) 73 } 74 err = proc.Signal(syscall.Signal(0)) 75 if err != nil { 76 t.Errorf("OS reported error for running process: %v", err) 77 } 78} 79 80func TestProcessBadPID(t *testing.T) { 81 p, err := FindProcess(-1) 82 if err != nil { 83 t.Fatalf("unexpected FindProcess error: %v", err) 84 } 85 err = p.Signal(syscall.Signal(0)) 86 if err == nil { 87 t.Error("p.Signal succeeded unexpectedly") 88 } 89} 90