File: user_linux.go

package info (click to toggle)
witr 0.2.4%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 736 kB
  • sloc: sh: 79; makefile: 10
file content (41 lines) | stat: -rw-r--r-- 674 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//go:build linux

package proc

import (
	"os"
	"strconv"
	"strings"
	"syscall"
)

func readUser(pid int) string {
	path := "/proc/" + strconv.Itoa(pid)

	info, err := os.Stat(path)
	if err != nil {
		return "unknown"
	}

	stat, ok := info.Sys().(*syscall.Stat_t)
	if !ok {
		return "unknown"
	}

	uid := int(stat.Uid)
	if uid == 0 {
		return "root"
	}
	// Try to resolve username from /etc/passwd
	uidStr := strconv.Itoa(uid)
	passwd, err := os.ReadFile("/etc/passwd")
	if err == nil {
		for line := range strings.Lines(string(passwd)) {
			fields := strings.Split(line, ":")
			if len(fields) > 2 && fields[2] == uidStr {
				return fields[0]
			}
		}
	}
	return uidStr
}