github.com/guilhermebr/docker@v1.4.2-0.20150428121140-67da055cebca/pkg/pidfile/pidfile.go (about)

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