プロセスIDを格納する処理をPIDFILE。pidファイルは、通常の状況下で、次のような効果があります。
- 他のプロセスがpidファイル読み取りプロセスのPIDを実行して得ることができる(もちろん、他の動的なコマンドによって得ることができます)
- pidファイルをチェックするためのプロセスを開始する前に、いくつかのバックグラウンドプロセスを開始しまし防止(特に薬など)
ここでpidファイルの管理にどのようにドッキングウィンドウです。
package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
log "github.com/sirupsen/logrus"
)
func main() {
_, err := NewPIDFile("pid.file")
if err != nil {
log.Errorf("error to create the pid file failed:%s", err.Error())
}
}
// PIDFile stored the process id
type PIDFile struct {
path string
}
// just suit for linux
func processExists(pid string) bool {
if _, err := os.Stat(filepath.Join("/proc", pid)); err == nil {
return true
}
return false
}
func checkPIDFILEAlreadyExists(path string) error {
if pidByte, err := ioutil.ReadFile(path); err == nil {
pid := strings.TrimSpace(string(pidByte))
if processExists(pid) {
return fmt.Errorf("ensure the process:%s is not running pid file:%s", pid, path)
}
}
return nil
}
// NewPIDFile create the pid file
// 指定路径下生产 pidfile, 文件内容为 pid
func NewPIDFile(path string) (*PIDFile, error) {
if err := checkPIDFILEAlreadyExists(path); err != nil {
return nil, err
}
if err := os.MkdirAll(filepath.Dir(path), os.FileMode(0755)); err != nil {
return nil, err
}
if err := ioutil.WriteFile(path, []byte(fmt.Sprintf("%d", os.Getpid())), 0644); err != nil {
return nil, err
}
return &PIDFile{path: path}, nil
}
// Remove remove the pid file
func (file PIDFile) Remove() error {
return os.Remove(file.path)
}
ヒント:
- 異なるオペレーティングシステム本実施形態では、プロセスは同じであるか否かを判断する。ここでは、Linuxの存在下または非存在下でプロセスを検出するための方法であります