@@ -19,6 +19,8 @@ package daemon
19
19
20
20
import (
21
21
"fmt"
22
+ "io"
23
+ "io/ioutil"
22
24
"log"
23
25
"net"
24
26
"net/http"
@@ -39,16 +41,20 @@ const (
39
41
40
42
// NewCommand created a new `daemon` command
41
43
func NewCommand () * cobra.Command {
42
- return & cobra.Command {
44
+ cmd := & cobra.Command {
43
45
Use : "daemon" ,
44
46
Short : fmt .Sprintf ("Run as a daemon on port %s" , port ),
45
47
Long : "Running as a daemon the initialization of cores and libraries is done only once." ,
46
48
Example : " " + os .Args [0 ] + " daemon" ,
47
49
Args : cobra .NoArgs ,
48
50
Run : runDaemonCommand ,
49
51
}
52
+ cmd .Flags ().BoolVar (& autoclose , "autoclose" , false , "Do not daemonize (terminate daemon process when the parent process dies)" )
53
+ return cmd
50
54
}
51
55
56
+ var autoclose bool
57
+
52
58
func runDaemonCommand (cmd * cobra.Command , args []string ) {
53
59
s := grpc .NewServer ()
54
60
@@ -68,13 +74,20 @@ func runDaemonCommand(cmd *cobra.Command, args []string) {
68
74
// register the monitors service
69
75
srv_monitor .RegisterMonitorServer (s , & daemon.MonitorService {})
70
76
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
+
71
86
lis , err := net .Listen ("tcp" , port )
72
87
if err != nil {
73
88
log .Fatalf ("failed to listen: %v" , err )
74
89
}
75
90
if err := s .Serve (lis ); err != nil {
76
91
log .Fatalf ("failed to serve: %v" , err )
77
92
}
78
-
79
- fmt .Println ("Done serving" )
80
93
}
0 commit comments