Open moooofly opened 6 years ago
if cli.Pidfile != "" {
pf, err := pidfile.New(cli.Pidfile)
if err != nil {
return fmt.Errorf("Error starting daemon: %v", err) -- 1
}
defer func() {
if err := pf.Remove(); err != nil { -- 4
logrus.Error(err)
}
}()
}
func checkPIDFileAlreadyExists(path string) error {
if pidByte, err := ioutil.ReadFile(path); err == nil {
pidString := strings.TrimSpace(string(pidByte))
if pid, err := strconv.Atoi(pidString); err == nil {
if processExists(pid) {
return fmt.Errorf("pid file found, ensure hunter-agent is not running or delete %s", path) -- 3
}
}
}
return nil
}
// New creates a PIDfile using the specified path.
func New(path string) (*PIDFile, error) {
if err := checkPIDFileAlreadyExists(path); err != nil { -- 2
return nil, err
}
// Note MkdirAll returns nil if a directory already exists
if err := system.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 removes the PIDFile.
func (file PIDFile) Remove() error {
return os.Remove(file.path) -- 5
}
As the codes show above, if the daemon exit normally, pf.Remove()
will be called by defer
, unless it is killed brutally by kill -9
.
But even kill -9
, it seems that the daemon can still startup normally.
phenomenon
solution
todo
Need a better way to clear
/var/run/hunter-agent.pid
file.