Skip to content

Commit 60b6203

Browse files
committed
daemon: added --autoclose flag
This is useful when the cli daemon is launched from an external process to avoid leaving zombie process if the parent process unexpectedly dies.
1 parent 6e82992 commit 60b6203

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

Diff for: cli/daemon/daemon.go

+16-3
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ package daemon
1919

2020
import (
2121
"fmt"
22+
"io"
23+
"io/ioutil"
2224
"log"
2325
"net"
2426
"net/http"
@@ -39,16 +41,20 @@ const (
3941

4042
// NewCommand created a new `daemon` command
4143
func NewCommand() *cobra.Command {
42-
return &cobra.Command{
44+
cmd := &cobra.Command{
4345
Use: "daemon",
4446
Short: fmt.Sprintf("Run as a daemon on port %s", port),
4547
Long: "Running as a daemon the initialization of cores and libraries is done only once.",
4648
Example: " " + os.Args[0] + " daemon",
4749
Args: cobra.NoArgs,
4850
Run: runDaemonCommand,
4951
}
52+
cmd.Flags().BoolVar(&autoclose, "autoclose", false, "Do not daemonize (terminate daemon process when the parent process dies)")
53+
return cmd
5054
}
5155

56+
var autoclose bool
57+
5258
func runDaemonCommand(cmd *cobra.Command, args []string) {
5359
s := grpc.NewServer()
5460

@@ -68,13 +74,20 @@ func runDaemonCommand(cmd *cobra.Command, args []string) {
6874
// register the monitors service
6975
srv_monitor.RegisterMonitorServer(s, &daemon.MonitorService{})
7076

77+
if autoclose {
78+
// When parent process ends terminate also the daemon
79+
go func() {
80+
// stdin is closed when the controlling parent process ends
81+
_, _ = io.Copy(ioutil.Discard, os.Stdin)
82+
os.Exit(0)
83+
}()
84+
}
85+
7186
lis, err := net.Listen("tcp", port)
7287
if err != nil {
7388
log.Fatalf("failed to listen: %v", err)
7489
}
7590
if err := s.Serve(lis); err != nil {
7691
log.Fatalf("failed to serve: %v", err)
7792
}
78-
79-
fmt.Println("Done serving")
8093
}

0 commit comments

Comments
 (0)