Gomander is a Go process daemonization library based on Cobra, enabling your program to easily support foreground and background daemon modes with complete process lifecycle management.
start, stop, restart, reload, status subcommands-d flag to run process in backgroundgo get github.com/muleiwu/gomander
package main
import (
"fmt"
"time"
"github.com/muleiwu/gomander"
)
func main() {
gomander.Run(func() {
fmt.Println("Application starting...")
for {
time.Sleep(5 * time.Second)
fmt.Println("Running...")
}
})
}
func main() {
gomander.Run(func() {
// Your business logic
},
gomander.WithPidFile("./myapp.pid"),
gomander.WithLogFile("./myapp.log"),
)
}
After compiling your program, you can use the following subcommands:
go build -o myapp
# Run in foreground (logs output to terminal)
./myapp start
# Run as background daemon
./myapp start -d
# or
./myapp start --daemon
In daemon mode:
./gomander.log)./gomander.pid)./myapp stop
Reads the PID file and sends SIGTERM signal to gracefully stop the daemon process.
./myapp restart
Stops the currently running process, then restarts it in daemon mode.
./myapp reload
Sends SIGHUP signal to the daemon process, can be used to trigger configuration reload (requires reload logic implementation in business code).
./myapp status
Displays the current status of the daemon process, including:
| Option | Description | Default |
|---|---|---|
WithPidFile(path) | PID file path | ./gomander.pid |
WithLogFile(path) | Log file path | ./gomander.log |
myapp start → Execute user function directly → Logs output to terminal
myapp start -d → Fork child process → Parent process exits ↓ Child process (daemon) ↓ Create new session (setsid) ↓ Write PID file ↓ Redirect output to log file ↓ Execute user function
| Signal | Behavior |
|---|---|
| SIGTERM | Graceful exit, cleanup PID file |
| SIGINT | Graceful exit, cleanup PID file |
| SIGHUP | Trigger reload (does not exit process) |
See example/main.go for a complete example.
cd example
go build -o myapp
# Start daemon
./myapp start -d
# Check status
./myapp status
# View logs
tail -f myapp.log
# Reload configuration
./myapp reload
# Restart process
./myapp restart
# Stop process
./myapp stop
| Variable | Description |
|---|---|
GOMANDER_DAEMON=1 | Internal use, identifies current process as daemon child process |
restart command waits for original process to exit (maximum 10 seconds) before starting new processMIT