From 261e26761805e03c126bf3934a8f39302e8d85fb Mon Sep 17 00:00:00 2001 From: Moritz Poldrack Date: Fri, 16 Jun 2023 21:12:25 +0000 Subject: [PATCH] os/exec: document a method to check if a process is alive Fixes #34396 Change-Id: I35c4e3447f84e349adf7edba92ccb19b324bfe14 GitHub-Last-Rev: 4f06764109ddd9bdfbe4841fc1bebebe026eeb29 GitHub-Pull-Request: golang/go#60763 Reviewed-on: https://go-review.googlesource.com/c/go/+/502815 TryBot-Result: Gopher Robot Reviewed-by: Dmitri Shuralyov Run-TryBot: Ian Lance Taylor Reviewed-by: Ian Lance Taylor Run-TryBot: Ian Lance Taylor Auto-Submit: Ian Lance Taylor --- src/os/exec.go | 4 +++- src/os/exec_unix_test.go | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/os/exec.go b/src/os/exec.go index d01ca592baefe..ed5a75c4d13f8 100644 --- a/src/os/exec.go +++ b/src/os/exec.go @@ -86,7 +86,9 @@ func Getppid() int { return syscall.Getppid() } // about the underlying operating system process. // // On Unix systems, FindProcess always succeeds and returns a Process -// for the given pid, regardless of whether the process exists. +// for the given pid, regardless of whether the process exists. To test whether +// the process actually exists, see whether p.Signal(syscall.Signal(0)) reports +// an error. func FindProcess(pid int) (*Process, error) { return findProcess(pid) } diff --git a/src/os/exec_unix_test.go b/src/os/exec_unix_test.go index 82c072a746dc3..26045192ff655 100644 --- a/src/os/exec_unix_test.go +++ b/src/os/exec_unix_test.go @@ -9,6 +9,7 @@ package os_test import ( "internal/testenv" . "os" + "syscall" "testing" ) @@ -25,3 +26,20 @@ func TestErrProcessDone(t *testing.T) { t.Errorf("got %v want %v", got, ErrProcessDone) } } + +func TestUNIXProcessAlive(t *testing.T) { + testenv.MustHaveGoBuild(t) + t.Parallel() + + p, err := StartProcess(testenv.GoToolPath(t), []string{"sleep", "1"}, &ProcAttr{}) + if err != nil { + t.Skipf("starting test process: %v", err) + } + defer p.Kill() + + proc, _ := FindProcess(p.Pid) + err = proc.Signal(syscall.Signal(0)) + if err != nil { + t.Errorf("OS reported error for running process: %v", err) + } +}