pidfile.go 871 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package pidfile
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. "path/filepath"
  7. "strconv"
  8. )
  9. type PidFile struct {
  10. path string
  11. }
  12. func checkPidFileAlreadyExists(path string) error {
  13. if pidString, err := ioutil.ReadFile(path); err == nil {
  14. if pid, err := strconv.Atoi(string(pidString)); err == nil {
  15. if _, err := os.Stat(filepath.Join("/proc", string(pid))); err == nil {
  16. return fmt.Errorf("pid file found, ensure docker is not running or delete %s", path)
  17. }
  18. }
  19. }
  20. return nil
  21. }
  22. func New(path string) (*PidFile, error) {
  23. if err := checkPidFileAlreadyExists(path); err != nil {
  24. return nil, err
  25. }
  26. if err := ioutil.WriteFile(path, []byte(fmt.Sprintf("%d", os.Getpid())), 0644); err != nil {
  27. return nil, err
  28. }
  29. return &PidFile{path: path}, nil
  30. }
  31. func (file PidFile) Remove() error {
  32. if err := os.Remove(file.path); err != nil {
  33. return err
  34. }
  35. return nil
  36. }