github.com/tompao/docker@v1.9.1/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  )
    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 pidString, err := ioutil.ReadFile(path); err == nil {
    21  		if pid, err := strconv.Atoi(string(pidString)); err == nil {
    22  			if _, err := os.Stat(filepath.Join("/proc", string(pid))); err == nil {
    23  				return fmt.Errorf("pid file found, ensure docker is not running or delete %s", path)
    24  			}
    25  		}
    26  	}
    27  	return nil
    28  }
    29  
    30  // New creates a PIDfile using the specified path.
    31  func New(path string) (*PIDFile, error) {
    32  	if err := checkPIDFileAlreadyExists(path); err != nil {
    33  		return nil, err
    34  	}
    35  	if err := ioutil.WriteFile(path, []byte(fmt.Sprintf("%d", os.Getpid())), 0644); err != nil {
    36  		return nil, err
    37  	}
    38  
    39  	return &PIDFile{path: path}, nil
    40  }
    41  
    42  // Remove removes the PIDFile.
    43  func (file PIDFile) Remove() error {
    44  	if err := os.Remove(file.path); err != nil {
    45  		return err
    46  	}
    47  	return nil
    48  }