proc.go 970 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package proc
  2. import (
  3. "github.com/coroot/coroot-node-agent/cgroup"
  4. "os"
  5. "path"
  6. "strconv"
  7. )
  8. var root = "/proc"
  9. func Path(pid uint32, subpath ...string) string {
  10. return path.Join(append([]string{root, strconv.Itoa(int(pid))}, subpath...)...)
  11. }
  12. func HostPath(p string) string {
  13. return Path(1, "root", p)
  14. }
  15. func GetCmdline(pid uint32) []byte {
  16. cmdline, err := os.ReadFile(Path(pid, "cmdline"))
  17. if err != nil {
  18. return nil
  19. }
  20. return cmdline
  21. }
  22. func ReadCgroup(pid uint32) (*cgroup.Cgroup, error) {
  23. return cgroup.NewFromProcessCgroupFile(Path(pid, "cgroup"))
  24. }
  25. func ListPids() ([]uint32, error) {
  26. root, err := os.Open(root)
  27. if err != nil {
  28. return nil, err
  29. }
  30. defer root.Close()
  31. dirs, err := root.Readdirnames(0)
  32. if err != nil {
  33. return nil, err
  34. }
  35. res := make([]uint32, 0, len(dirs))
  36. for _, dir := range dirs {
  37. pid64, err := strconv.ParseUint(dir, 10, 32)
  38. if err != nil {
  39. continue
  40. }
  41. res = append(res, uint32(pid64))
  42. }
  43. return res, nil
  44. }