pid.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package ncutils
  2. import (
  3. "fmt"
  4. "os"
  5. "strconv"
  6. )
  7. // PIDFILE - path/name of pid file
  8. const PIDFILE = "/var/run/netclient.pid"
  9. // WindowsPIDError - error returned from pid function on windows
  10. type WindowsPIDError struct{}
  11. // Error generates error for windows os
  12. func (*WindowsPIDError) Error() string {
  13. return "pid tracking not supported on windows"
  14. }
  15. // SavePID - saves the pid of running program to disk
  16. func SavePID() error {
  17. if IsWindows() {
  18. return &WindowsPIDError{}
  19. }
  20. pid := os.Getpid()
  21. if err := os.WriteFile(PIDFILE, []byte(fmt.Sprintf("%d", pid)), 0644); err != nil {
  22. return fmt.Errorf("could not write to pid file %w", err)
  23. }
  24. return nil
  25. }
  26. // ReadPID - reads a previously saved pid from disk
  27. func ReadPID() (int, error) {
  28. if IsWindows() {
  29. return 0, &WindowsPIDError{}
  30. }
  31. bytes, err := os.ReadFile(PIDFILE)
  32. if err != nil {
  33. return 0, fmt.Errorf("could not read pid file %w", err)
  34. }
  35. pid, err := strconv.Atoi(string(bytes))
  36. if err != nil {
  37. return 0, fmt.Errorf("pid file contents invalid %w", err)
  38. }
  39. return pid, nil
  40. }