llmongodb/pid.go

86 lines
1.5 KiB
Go
Raw Normal View History

2015-07-30 15:55:32 +02:00
// pid
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
2015-07-30 15:55:32 +02:00
"os"
"path"
"strconv"
"strings"
)
2015-07-30 16:53:24 +02:00
var (
pid = PID{}
)
2016-10-05 11:55:50 +02:00
// PID structure
2015-07-30 15:55:32 +02:00
type PID struct {
PID string
PIDFile string
}
2015-10-16 11:43:18 +02:00
// verifica se esiste il PIDFile;
// se esiste legge il PID e controlla se e' running il processo associato
2015-07-30 15:55:32 +02:00
func (p *PID) check() bool {
bpid, err := ioutil.ReadFile(p.PIDFile)
p.PID = strings.TrimRight(string(bpid), "\n")
if err == nil && p.readCmd() {
return true
}
return false
}
2015-10-16 11:43:18 +02:00
// controlla se esiste il processo associato al PID,
// se il cmd e' lo stesso e se e' in esecuzione.
2015-07-30 15:55:32 +02:00
func (p *PID) readCmd() bool {
bcmd, err := ioutil.ReadFile(path.Join("/proc", p.PID, "cmdline"))
2015-07-30 16:53:24 +02:00
// non esiste la dir relativa al PID su /proc
2015-07-30 15:55:32 +02:00
if err != nil {
fmt.Println("cmdline error: ", err)
return false
}
cmd := bytes.Trim(bcmd, "\x00")
2016-10-05 11:55:50 +02:00
if !strings.Contains(string(cmd), opts.Exe) {
2015-07-30 15:55:32 +02:00
fmt.Printf("PID %s used by %s\n", pid, cmd)
}
return true
}
2015-10-16 11:43:18 +02:00
// scrive il PID nel PIDFile
func (p *PID) Write(l bool) {
2015-07-30 15:55:32 +02:00
if p.check() {
if l {
log.Println("Running: ", p.PID)
} else {
fmt.Println("Running: ", p.PID)
}
2015-07-30 15:55:32 +02:00
os.Exit(-6)
}
fpid, err := os.OpenFile(p.PIDFile, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
if l {
log.Println("PID file error: ", err.Error())
} else {
fmt.Println("PID file error: ", err.Error())
}
2015-07-30 15:55:32 +02:00
os.Exit(-5)
}
fpid.WriteString(strconv.Itoa(os.Getpid()))
fpid.Close()
}
2016-10-05 11:55:50 +02:00
// Remove cancella il PIDFile
2015-07-30 15:55:32 +02:00
func (p *PID) Remove() {
err := os.Remove(p.PIDFile)
if err != nil {
fmt.Println("RM file error: ", err.Error())
2015-07-30 15:55:32 +02:00
}
}