pidfile.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. func checkPIDFileAlreadyExists(path string) error {
  13. pidByte, err := os.ReadFile(path)
  14. if err != nil {
  15. if os.IsNotExist(err) {
  16. return nil
  17. }
  18. return err
  19. }
  20. pid, err := strconv.Atoi(string(bytes.TrimSpace(pidByte)))
  21. if err == nil && process.Alive(pid) {
  22. return fmt.Errorf("pid file found, ensure docker is not running or delete %s", path)
  23. }
  24. return nil
  25. }
  26. // Write writes a "PID file" at the specified path. It returns an error if the
  27. // file exists and contains a valid PID of a running process, or when failing
  28. // to write the file.
  29. func Write(path string, pid int) error {
  30. if pid < 1 {
  31. // We might be running as PID 1 when running docker-in-docker,
  32. // but 0 or negative PIDs are not acceptable.
  33. return fmt.Errorf("invalid PID (%d): only positive PIDs are allowed", pid)
  34. }
  35. if err := checkPIDFileAlreadyExists(path); err != nil {
  36. return err
  37. }
  38. return os.WriteFile(path, []byte(strconv.Itoa(pid)), 0o644)
  39. }