gopkg.in/docker/docker.v20@v20.10.27/pkg/pidfile/pidfile.go (about) 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 6 import ( 7 "fmt" 8 "os" 9 "path/filepath" 10 "strconv" 11 "strings" 12 13 "github.com/docker/docker/pkg/system" 14 ) 15 16 // PIDFile is a file used to store the process ID of a running process. 17 type PIDFile struct { 18 path string 19 } 20 21 func checkPIDFileAlreadyExists(path string) error { 22 if pidByte, err := os.ReadFile(path); err == nil { 23 pidString := strings.TrimSpace(string(pidByte)) 24 if pid, err := strconv.Atoi(pidString); err == nil { 25 if processExists(pid) { 26 return fmt.Errorf("pid file found, ensure docker is not running or delete %s", path) 27 } 28 } 29 } 30 return nil 31 } 32 33 // New creates a PIDfile using the specified path. 34 func New(path string) (*PIDFile, error) { 35 if err := checkPIDFileAlreadyExists(path); err != nil { 36 return nil, err 37 } 38 // Note MkdirAll returns nil if a directory already exists 39 if err := system.MkdirAll(filepath.Dir(path), os.FileMode(0755)); err != nil { 40 return nil, err 41 } 42 if err := os.WriteFile(path, []byte(fmt.Sprintf("%d", os.Getpid())), 0644); err != nil { 43 return nil, err 44 } 45 46 return &PIDFile{path: path}, nil 47 } 48 49 // Remove removes the PIDFile. 50 func (file PIDFile) Remove() error { 51 return os.Remove(file.path) 52 }