[process][windows] Retrieve process name as basename of executable

We align ourself with psutil
8e4099d9f0/psutil/_pswindows.py (L749-L759)

Benchmarks show vast improvements

    go test -run=BenchmarkProcessName -bench=BenchmarkProcessName ./process
    goos: windows
    goarch: amd64
    pkg: github.com/shirou/gopsutil/v3/process
    cpu: Intel(R) Core(TM) i5-6300U CPU @ 2.40GHz
    BenchmarkProcessName-4               180           6564033 ns/op
    BenchmarkProcessNameViaExe-4       22111             51153 ns/op
    PASS
    ok      github.com/shirou/gopsutil/v3/process   3.914s

Fixes #1368
pull/1369/head
Lomanic 3 years ago
parent bd4529a7cc
commit 980cc82c08

@ -294,7 +294,7 @@ func Test_Process_Name(t *testing.T) {
t.Errorf("getting name error %v", err) t.Errorf("getting name error %v", err)
} }
if !strings.Contains(n, "process.test") { if !strings.Contains(n, "process.test") {
t.Errorf("invalid Exe %s", n) t.Errorf("invalid Name %s", n)
} }
} }

@ -10,6 +10,7 @@ import (
"fmt" "fmt"
"io" "io"
"os" "os"
"path/filepath"
"reflect" "reflect"
"strings" "strings"
"syscall" "syscall"
@ -319,18 +320,19 @@ func (p *Process) PpidWithContext(ctx context.Context) (int32, error) {
} }
func (p *Process) NameWithContext(ctx context.Context) (string, error) { func (p *Process) NameWithContext(ctx context.Context) (string, error) {
ppid, _, name, err := getFromSnapProcess(p.Pid) if p.Pid == 0 {
if err != nil { return "System Idle Process", nil
return "", fmt.Errorf("could not get Name: %s", err) }
if p.Pid == 4 {
return "System", nil
} }
// if no errors and not cached already, cache ppid exe, err := p.ExeWithContext(ctx)
p.parent = ppid if err != nil {
if 0 == p.getPpid() { return "", fmt.Errorf("could not get Name: %s", err)
p.setPpid(ppid)
} }
return name, nil return filepath.Base(exe), nil
} }
func (p *Process) TgidWithContext(ctx context.Context) (int32, error) { func (p *Process) TgidWithContext(ctx context.Context) (int32, error) {

Loading…
Cancel
Save