fix pidfile handling

This commit is contained in:
andrzej 2024-11-05 15:28:39 +01:00
parent 34ddba17c1
commit 7bdef46ab9
1 changed files with 11 additions and 14 deletions

25
main.go
View File

@ -1,12 +1,11 @@
package main package main
import ( import (
"bytes"
"encoding/binary"
"flag" "flag"
"log" "log"
"os" "os"
"os/exec" "os/exec"
"strconv"
"sync" "sync"
) )
@ -39,19 +38,20 @@ func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile | log.Lmicroseconds) log.SetFlags(log.LstdFlags | log.Lshortfile | log.Lmicroseconds)
log.Println("Welcome to GoPaper!") log.Println("Welcome to GoPaper!")
killPrevProc() err = killPrevProc()
if err != nil {
log.Println("error attempting to kill pre-existing process: ", err)
cleanExit(1)
}
//create new pidfile //create new pidfile
pid := os.Getpid() pid := strconv.FormatInt(int64(os.Getpid()), 10)
log.Printf("pid: %v", pid)
pidfile, err := os.Create(pidfilePath) pidfile, err := os.Create(pidfilePath)
if err != nil { if err != nil {
log.Println("error trying to create pidfile:", err) log.Println("error trying to create pidfile:", err)
cleanExit(1) cleanExit(1)
} }
buf := new(bytes.Buffer) pidfile.WriteString(pid)
err = binary.Write(buf, binary.LittleEndian, pid)
if err != nil {
}
pidfile.Write(buf.Bytes())
var waitGroup sync.WaitGroup var waitGroup sync.WaitGroup
waitGroup.Add(1) waitGroup.Add(1)
@ -128,17 +128,14 @@ func killPrevProc() error {
return err return err
} }
//kill process //kill process
//BUG: kill command doesn't work. prexPid == [] err = exec.Command("kill", string(prexPid)).Run()
err = exec.Command("kill", "-9", string(prexPid)).Run()
if err != nil { if err != nil {
log.Printf("unable to kill process %v\n", string(prexPid)) log.Printf("Error attempting to kill process %v: %v\n", string(prexPid), err)
return err
} }
//remove pidfile //remove pidfile
err = os.Remove(pidfilePath) err = os.Remove(pidfilePath)
if err != nil { if err != nil {
log.Printf("unable to remove pidfile %v\n", pidfilePath) log.Printf("unable to remove pidfile %v\n", pidfilePath)
return err
} }
return nil return nil
} }