github.com/gunjan5/docker@v1.8.2/pkg/pidfile/pidfile.go (about)

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