From 15c27e16cc5c889cc68cc671c0799f54888907a9 Mon Sep 17 00:00:00 2001 From: Sergey Krashevich Date: Sat, 24 Feb 2024 10:33:02 +0300 Subject: [PATCH] feat(app): support daemon mode on non-Windows platforms Added a new command-line flag `-daemon` to run the application in the background as a daemon. This option is only available for non-Windows operating systems due to platform-specific process handling. When enabled, the application restarts itself with the same arguments except for the `-daemon` flag, prints the PID of the background process, and then exits the current process. --- internal/app/app.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/internal/app/app.go b/internal/app/app.go index b27437db..c242ae33 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -5,6 +5,7 @@ import ( "flag" "fmt" "os" + "os/exec" "path/filepath" "runtime" "strings" @@ -25,8 +26,14 @@ var Info = map[string]any{ func Init() { var confs Config var version bool + var daemon bool flag.Var(&confs, "config", "go2rtc config (path to file or raw text), support multiple") + if runtime.GOOS != "windows" { + flag.BoolVar(&daemon, "daemon", false, "Run program in background") + } else { + daemon = false + } flag.BoolVar(&version, "version", false, "Print the version of the application and exit") flag.Parse() @@ -35,6 +42,14 @@ func Init() { os.Exit(0) } + if daemon { + // Re-run the program in background and exit + cmd := exec.Command(os.Args[0], os.Args[2:]...) + cmd.Start() + fmt.Println("Running in daemon mode with PID:", cmd.Process.Pid) + os.Exit(0) + } + if confs == nil { confs = []string{"go2rtc.yaml"} }