Skip to content

Commit 459eb09

Browse files
committed
refactor Stop() function for better use outside package
1 parent 0df1e51 commit 459eb09

File tree

2 files changed

+30
-21
lines changed

2 files changed

+30
-21
lines changed

actions.go

Lines changed: 9 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package daemonigo
33
import (
44
"fmt"
55
"os"
6-
"time"
76
)
87

98
// Daemon default actions.
@@ -26,7 +25,7 @@ var actions = map[string]func(){
2625
case !isRunning:
2726
fmt.Println(AppName + " is NOT running or already stopped")
2827
default:
29-
Stop(process)
28+
stop(process)
3029
}
3130
},
3231
"status": func() {
@@ -46,7 +45,7 @@ var actions = map[string]func(){
4645
return
4746
}
4847
if isRunning {
49-
Stop(process)
48+
stop(process)
5049
}
5150
start()
5251
},
@@ -58,31 +57,20 @@ func printStatusErr(e error) {
5857
fmt.Println("Details:", e.Error())
5958
}
6059

61-
// Helper function to operate with errors in actions.
60+
// Helper function to operate with errors printing in actions.
6261
func failed(e error) {
6362
fmt.Println("FAILED")
6463
fmt.Println("Details:", e.Error())
6564
}
6665

67-
// Stops daemon process.
68-
//
69-
// This function can also be used when writing own daemon actions.
70-
func Stop(process *os.Process) {
66+
// Helper function which wraps Stop() with printing
67+
// for using in daemon default actions.
68+
func stop(process *os.Process) {
7169
fmt.Printf("Stopping %s...", AppName)
72-
if err := process.Signal(os.Interrupt); err != nil {
70+
if err := Stop(process); err != nil {
7371
failed(err)
74-
return
75-
}
76-
for {
77-
time.Sleep(200 * time.Millisecond)
78-
switch isRunning, _, err := Status(); {
79-
case err != nil:
80-
printStatusErr(err)
81-
return
82-
case !isRunning:
83-
fmt.Println("OK")
84-
return
85-
}
72+
} else {
73+
fmt.Println("OK")
8674
}
8775
}
8876

daemoni.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,3 +204,24 @@ func Start(timeout uint8) (success bool, e error) {
204204
}
205205
return
206206
}
207+
208+
// Stops daemon process.
209+
// Sends signal os.Interrupt to daemonized process.
210+
//
211+
// This function can also be used when writing your own daemon actions.
212+
func Stop(process *os.Process) (e error){
213+
if err := process.Signal(os.Interrupt); err != nil {
214+
e = fmt.Errorf("daemonigo.Stop(): failed to send interrupt signal to %s, reason -> %s", AppName, err.Error())
215+
return
216+
}
217+
for {
218+
time.Sleep(200 * time.Millisecond)
219+
switch isRunning, _, err := Status(); {
220+
case err != nil:
221+
e = fmt.Errorf("daemonigo.Stop(): checking status of %s failed, reason -> %s", AppName, err.Error())
222+
return
223+
case !isRunning:
224+
return
225+
}
226+
}
227+
}

0 commit comments

Comments
 (0)