summaryrefslogtreecommitdiff
path: root/daemonize.go
diff options
context:
space:
mode:
authorJakob Unterwurzacher2015-10-11 18:02:48 +0200
committerJakob Unterwurzacher2015-10-11 18:02:48 +0200
commit14115b061b253f3c58eee731e3b38dbb18fcf1fa (patch)
tree26592191dca7e5d1c469d1e7f5674634b0ecf81e /daemonize.go
parent39183bea00f0d064f0cb96427dff150799d1dbe5 (diff)
Add native daemonization
Diffstat (limited to 'daemonize.go')
-rw-r--r--daemonize.go47
1 files changed, 47 insertions, 0 deletions
diff --git a/daemonize.go b/daemonize.go
new file mode 100644
index 0000000..87faf33
--- /dev/null
+++ b/daemonize.go
@@ -0,0 +1,47 @@
+package main
+
+import (
+ "syscall"
+ "os/exec"
+ "os"
+ "fmt"
+ "os/signal"
+)
+
+// The child sends us USR1 if the mount was successful
+func waitForUsr1() {
+ c := make(chan os.Signal, 1)
+ signal.Notify(c, syscall.SIGUSR1)
+ <-c
+ os.Exit(0)
+}
+
+// daemonize - execute ourselves once again, this time with the "-f" flag, and
+// wait for SIGUSR1.
+func daemonize() {
+ go waitForUsr1()
+ name := os.Args[0]
+ newArgs := []string{"-f"}
+ newArgs = append(newArgs, os.Args[1:]...)
+ c := exec.Command(name, newArgs...)
+ c.Stdout = os.Stdout
+ c.Stderr = os.Stderr
+ c.Stdin = os.Stdin
+ err := c.Start()
+ if err != nil {
+ fmt.Printf("daemonize: starting %s failed: %v\n", name)
+ os.Exit(1)
+ }
+ err = c.Wait()
+ if err != nil {
+ if exiterr, ok := err.(*exec.ExitError); ok {
+ if waitstat, ok := exiterr.Sys().(syscall.WaitStatus); ok {
+ os.Exit(waitstat.ExitStatus())
+ }
+ }
+ fmt.Printf("daemonize: wait returned an unknown error: %v\n", err)
+ os.Exit(1)
+ }
+ // The child exited with 0 - let's do the same.
+ os.Exit(0)
+}