summaryrefslogtreecommitdiffhomepage
path: root/util/pidowner/pidowner_linux.go
blob: f3f5cd97ddcb289e0f647d524b9cc7cb4e72704b (plain)
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
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause

package pidowner

import (
	"fmt"
	"os"
	"strings"

	"tailscale.com/util/lineiter"
)

func ownerOfPID(pid int) (userID string, err error) {
	file := fmt.Sprintf("/proc/%d/status", pid)
	for lr := range lineiter.File(file) {
		line, err := lr.Value()
		if err != nil {
			if os.IsNotExist(err) {
				return "", ErrProcessNotFound
			}
			return "", err
		}
		if len(line) < 4 || string(line[:4]) != "Uid:" {
			continue
		}
		f := strings.Fields(string(line))
		if len(f) >= 2 {
			userID = f[1] // real userid
		}
	}
	if userID == "" {
		return "", fmt.Errorf("missing Uid line in %s", file)
	}
	return userID, nil
}