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