Skip to content

Xiami2012/pidfile-go

Repository files navigation

pidfile-go

Go Reference Golang-CI

This is a go package to manage your instance/service’s PID file.

Install

go get github.com/Xiami2012/pidfile-go@latest

Basic usage

func main() {
	if err := pidfile.Write("/run/your_instance_name.pid"); err != nil {
		if errors.Is(err, pidfile.ErrPIDFileInUse) {
			fmt.Printf("Instance/Service is already running. Exiting.")
			os.Exit(1)
		}
		panic(fmt.Sprintf("Failed to create PIDFile: %s\n", err.Error()))
	}
	defer pidfile.Remove("/run/your_instance_name.pid")
}

Why reinventing the wheel

Once I have a daemon running in system without registering to any system service manager (run by some scripts during boot).

To add a self-update feature, I need to know the old running PID and gracefully kill it before running the updated one.

Searched and didn’t find a package having something like GetPID() which does both reading the PID file and verifies it is running the desired process.

TODO

  • Allow to specify compared executable name instead of current process’s

  • Allow to specify PID instead of current process’s

  • Add lock version APIs (By using flock / LockFile)