github.com/reds/docker@v1.11.2-rc1/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 5 6 import ( 7 "fmt" 8 "io/ioutil" 9 "os" 10 "path/filepath" 11 "strconv" 12 "strings" 13 ) 14 15 // PIDFile is a file used to store the process ID of a running process. 16 type PIDFile struct { 17 path string 18 } 19 20 func checkPIDFileAlreadyExists(path string) error { 21 if pidByte, err := ioutil.ReadFile(path); err == nil { 22 pidString := strings.TrimSpace(string(pidByte)) 23 if pid, err := strconv.Atoi(pidString); err == nil { 24 if _, err := os.Stat(filepath.Join("/proc", strconv.Itoa(pid))); err == nil { 25 return fmt.Errorf("pid file found, ensure docker is not running or delete %s", path) 26 } 27 } 28 } 29 return nil 30 } 31 32 // New creates a PIDfile using the specified path. 33 func New(path string) (*PIDFile, error) { 34 if err := checkPIDFileAlreadyExists(path); err != nil { 35 return nil, err 36 } 37 if err := ioutil.WriteFile(path, []byte(fmt.Sprintf("%d", os.Getpid())), 0644); err != nil { 38 return nil, err 39 } 40 41 return &PIDFile{path: path}, nil 42 } 43 44 // Remove removes the PIDFile. 45 func (file PIDFile) Remove() error { 46 if err := os.Remove(file.path); err != nil { 47 return err 48 } 49 return nil 50 }