pidfile.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Package pidfile provides structure and helper functions to create and remove
  2. // PID file. A PID file is usually a file used to store the process ID of a
  3. // running process.
  4. package pidfile // import "github.com/docker/docker/pkg/pidfile"
  5. import (
  6. "bytes"
  7. "fmt"
  8. "os"
  9. "strconv"
  10. "github.com/docker/docker/pkg/process"
  11. )
  12. // Read reads the "PID file" at path, and returns the PID if it contains a
  13. // valid PID of a running process, or 0 otherwise. It returns an error when
  14. // failing to read the file, or if the file doesn't exist, but malformed content
  15. // is ignored. Consumers should therefore check if the returned PID is a non-zero
  16. // value before use.
  17. func Read(path string) (pid int, err error) {
  18. pidByte, err := os.ReadFile(path)
  19. if err != nil {
  20. return 0, err
  21. }
  22. pid, err = strconv.Atoi(string(bytes.TrimSpace(pidByte)))
  23. if err != nil {
  24. return 0, nil
  25. }
  26. if pid != 0 && process.Alive(pid) {
  27. return pid, nil
  28. }
  29. return 0, nil
  30. }
  31. // Write writes a "PID file" at the specified path. It returns an error if the
  32. // file exists and contains a valid PID of a running process, or when failing
  33. // to write the file.
  34. func Write(path string, pid int) error {
  35. if pid < 1 {
  36. // We might be running as PID 1 when running docker-in-docker,
  37. // but 0 or negative PIDs are not acceptable.
  38. return fmt.Errorf("invalid PID (%d): only positive PIDs are allowed", pid)
  39. }
  40. oldPID, err := Read(path)
  41. if err != nil && !os.IsNotExist(err) {
  42. return err
  43. }
  44. if oldPID != 0 {
  45. return fmt.Errorf("process with PID %d is still running", oldPID)
  46. }
  47. return os.WriteFile(path, []byte(strconv.Itoa(pid)), 0o644)
  48. }