llmongodb/pid.go

66 lines
1 KiB
Go
Raw Normal View History

2015-07-30 15:55:32 +02:00
// pid
package main
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path"
"strconv"
"strings"
)
type PID struct {
PID string
PIDFile string
}
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
}
func (p *PID) readCmd() bool {
bcmd, err := ioutil.ReadFile(path.Join("/proc", p.PID, "cmdline"))
if err != nil {
fmt.Println("cmdline error: ", err)
return false
}
cmd := bytes.Trim(bcmd, "\x00")
if strings.Contains(string(cmd), opts.Exe) {
return true
} else {
fmt.Printf("PID %s used by %s\n", pid, cmd)
return true
}
return true
}
func (p *PID) Write() {
if p.check() {
fmt.Println("Running: ", p.PID)
os.Exit(-6)
}
fpid, err := os.OpenFile(p.PIDFile, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Println("PID file error: ", err.Error())
os.Exit(-5)
}
fpid.WriteString(strconv.Itoa(os.Getpid()))
fpid.Close()
}
func (p *PID) Remove() {
err := os.Remove(p.PIDFile)
if err != nil {
}
}