From 8dec3d81f3f13aed22d30d20ce05f2d2cb09a9d4 Mon Sep 17 00:00:00 2001 From: Ilya Prudnikov Date: Fri, 17 Jan 2020 13:06:07 +0200 Subject: [PATCH] Fix check pid existence when running in different process namespace (container) --- process/process_posix.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/process/process_posix.go b/process/process_posix.go index 13f0308..9d0ec83 100644 --- a/process/process_posix.go +++ b/process/process_posix.go @@ -12,6 +12,7 @@ import ( "strings" "syscall" + "github.com/shirou/gopsutil/internal/common" "golang.org/x/sys/unix" ) @@ -78,6 +79,16 @@ func PidExistsWithContext(ctx context.Context, pid int32) (bool, error) { if err != nil { return false, err } + + if _, err := os.Stat(common.HostProc()); err == nil { //Means that proc filesystem exist + // Checking PID existence based on existence of //proc/ folder + // This covers the case when running inside container with a different process namespace (by default) + _, err := os.Stat(common.HostProc(strconv.Itoa(int(pid)))) + return err == nil, err + } + + //'/proc' filesystem is not exist, checking of PID existence is done via signalling the process + //Make sense only if we run in the same process namespace err = proc.Signal(syscall.Signal(0)) if err == nil { return true, nil @@ -95,6 +106,7 @@ func PidExistsWithContext(ctx context.Context, pid int32) (bool, error) { case syscall.EPERM: return true, nil } + return false, err }