pidowner_linux.go 700 B

123456789101112131415161718192021222324252627282930313233343536
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package pidowner
  4. import (
  5. "fmt"
  6. "os"
  7. "strings"
  8. "tailscale.com/util/lineiter"
  9. )
  10. func ownerOfPID(pid int) (userID string, err error) {
  11. file := fmt.Sprintf("/proc/%d/status", pid)
  12. for lr := range lineiter.File(file) {
  13. line, err := lr.Value()
  14. if err != nil {
  15. if os.IsNotExist(err) {
  16. return "", ErrProcessNotFound
  17. }
  18. return "", err
  19. }
  20. if len(line) < 4 || string(line[:4]) != "Uid:" {
  21. continue
  22. }
  23. f := strings.Fields(string(line))
  24. if len(f) >= 2 {
  25. userID = f[1] // real userid
  26. }
  27. }
  28. if userID == "" {
  29. return "", fmt.Errorf("missing Uid line in %s", file)
  30. }
  31. return userID, nil
  32. }