Skip to content

Commit

Permalink
[process][windows] Retrieve process name as basename of executable
Browse files Browse the repository at this point in the history
We align ourself with psutil
https://github.com/giampaolo/psutil/blob/8e4099d9f063ceb4ee3da5845562c5b934f83544/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 shirou#1368
  • Loading branch information
Lomanic committed Oct 22, 2022
1 parent bd4529a commit 980cc82
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 9 deletions.
2 changes: 1 addition & 1 deletion process/process_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ func Test_Process_Name(t *testing.T) {
t.Errorf("getting name error %v", err)
}
if !strings.Contains(n, "process.test") {
t.Errorf("invalid Exe %s", n)
t.Errorf("invalid Name %s", n)
}
}

Expand Down
18 changes: 10 additions & 8 deletions process/process_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"fmt"
"io"
"os"
"path/filepath"
"reflect"
"strings"
"syscall"
Expand Down Expand Up @@ -319,18 +320,19 @@ func (p *Process) PpidWithContext(ctx context.Context) (int32, error) {
}

func (p *Process) NameWithContext(ctx context.Context) (string, error) {
ppid, _, name, err := getFromSnapProcess(p.Pid)
if err != nil {
return "", fmt.Errorf("could not get Name: %s", err)
if p.Pid == 0 {
return "System Idle Process", nil
}
if p.Pid == 4 {
return "System", nil
}

// if no errors and not cached already, cache ppid
p.parent = ppid
if 0 == p.getPpid() {
p.setPpid(ppid)
exe, err := p.ExeWithContext(ctx)
if err != nil {
return "", fmt.Errorf("could not get Name: %s", err)
}

return name, nil
return filepath.Base(exe), nil
}

func (p *Process) TgidWithContext(ctx context.Context) (int32, error) {
Expand Down

0 comments on commit 980cc82

Please sign in to comment.