stat.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package procfs
  2. import (
  3. "bufio"
  4. "fmt"
  5. "strconv"
  6. "strings"
  7. )
  8. // Stat represents kernel/system statistics.
  9. type Stat struct {
  10. // Boot time in seconds since the Epoch.
  11. BootTime int64
  12. }
  13. // NewStat returns kernel/system statistics read from /proc/stat.
  14. func NewStat() (Stat, error) {
  15. fs, err := NewFS(DefaultMountPoint)
  16. if err != nil {
  17. return Stat{}, err
  18. }
  19. return fs.NewStat()
  20. }
  21. // NewStat returns an information about current kernel/system statistics.
  22. func (fs FS) NewStat() (Stat, error) {
  23. f, err := fs.open("stat")
  24. if err != nil {
  25. return Stat{}, err
  26. }
  27. defer f.Close()
  28. s := bufio.NewScanner(f)
  29. for s.Scan() {
  30. line := s.Text()
  31. if !strings.HasPrefix(line, "btime") {
  32. continue
  33. }
  34. fields := strings.Fields(line)
  35. if len(fields) != 2 {
  36. return Stat{}, fmt.Errorf("couldn't parse %s line %s", f.Name(), line)
  37. }
  38. i, err := strconv.ParseInt(fields[1], 10, 32)
  39. if err != nil {
  40. return Stat{}, fmt.Errorf("couldn't parse %s: %s", fields[1], err)
  41. }
  42. return Stat{BootTime: i}, nil
  43. }
  44. if err := s.Err(); err != nil {
  45. return Stat{}, fmt.Errorf("couldn't parse %s: %s", f.Name(), err)
  46. }
  47. return Stat{}, fmt.Errorf("couldn't parse %s, missing btime", f.Name())
  48. }