Skip to content

Commit 4f06764

Browse files
committed
os/exec: document method to check if a process is alive
Fixes #34396
1 parent b0e1707 commit 4f06764

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

src/os/exec.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,9 @@ func Getppid() int { return syscall.Getppid() }
8686
// about the underlying operating system process.
8787
//
8888
// On Unix systems, FindProcess always succeeds and returns a Process
89-
// for the given pid, regardless of whether the process exists.
89+
// for the given pid, regardless of whether the process exists. To test whether
90+
// the process actually exists, see whether p.Signal(syscall.Signal(0)) reports
91+
// an error.
9092
func FindProcess(pid int) (*Process, error) {
9193
return findProcess(pid)
9294
}

src/os/exec_unix_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ package os_test
99
import (
1010
"internal/testenv"
1111
. "os"
12+
"syscall"
1213
"testing"
1314
)
1415

@@ -25,3 +26,20 @@ func TestErrProcessDone(t *testing.T) {
2526
t.Errorf("got %v want %v", got, ErrProcessDone)
2627
}
2728
}
29+
30+
func TestUNIXProcessAlive(t *testing.T) {
31+
testenv.MustHaveGoBuild(t)
32+
t.Parallel()
33+
34+
p, err := StartProcess(testenv.GoToolPath(t), []string{"sleep", "1"}, &ProcAttr{})
35+
if err != nil {
36+
t.Skipf("starting test process: %v", err)
37+
}
38+
defer p.Kill()
39+
40+
proc, _ := FindProcess(p.Pid)
41+
err = proc.Signal(syscall.Signal(0))
42+
if err != nil {
43+
t.Errorf("OS reported error for running process: %v", err)
44+
}
45+
}

0 commit comments

Comments
 (0)