https://github.com/mevdschee/pidfile
A Go package for single-instance execution using a PID file
https://github.com/mevdschee/pidfile
go golang golang-package
Last synced: 6 months ago
JSON representation
A Go package for single-instance execution using a PID file
- Host: GitHub
- URL: https://github.com/mevdschee/pidfile
- Owner: mevdschee
- License: mit
- Created: 2025-01-29T20:27:25.000Z (12 months ago)
- Default Branch: main
- Last Pushed: 2025-03-19T01:40:31.000Z (10 months ago)
- Last Synced: 2025-04-22T22:18:29.196Z (9 months ago)
- Topics: go, golang, golang-package
- Language: Go
- Homepage:
- Size: 17.6 KB
- Stars: 5
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Pidfile package for Go
The `pidfile` package provides a simple way to ensure that only one instance of a Go application runs at any given time by using a file that contains a decimal number also known as the PID (short for process identifier).
## Features
- Detects that the an instance of the application is already running.
- Allows you to prevents multiple instances of the application from running concurrently.
- Signals the first instance of the application when a next instance is started.
- Passes the command line arguments of any next instance to the first instance.
## Installation
To install the `pidfile` package, use the following `go get` command:
go get github.com/mevdschee/pidfile
## Example
Here is an example of an application that uses the pidfile package to ensure single instance execution:
```go
package main
import (
"log"
"os"
"github.com/mevdschee/pidfile"
)
func main() {
// create pidfile struct based on identifier
pf := pidfile.New("app_identifier")
// when a second instance is started
pf.OnSecond = func(args []string) {
log.Printf("another instance was started")
}
// create pidfile on application start
err := pf.Create()
if err != nil {
log.Fatalf("can't create pidfile: %v", err)
}
// remove pidfile on application close
defer pf.Remove()
// if this is not the first instance, then close it
if pf.FirstPid != os.Getpid() {
return
}
// application code
}
```
NB: This package was built for usage in a (desktop) [Fyne](https://fyne.io/) project.
## Future work / Known issues
The following issues need addressing in future versions:
- Add parallel tests to validate starting once does not have race conditions
- Add parallel tests to validate arguments lock prevents race conditions
## Credits / related work
The following packages have inspired me to make this package:
- https://github.com/postfinance/single
- https://github.com/makifdb/pidfile