@@ -13,7 +13,7 @@ import (
13
13
"time"
14
14
15
15
"github.com/howeyc/fsnotify"
16
- "github.com/sbinet/pstree "
16
+ "github.com/mitchellh/go-ps "
17
17
"github.com/silenceper/log"
18
18
)
19
19
@@ -185,7 +185,7 @@ func Kill() {
185
185
func killAllProcesses (pid int ) (err error ) {
186
186
hasAllKilled := make (chan bool )
187
187
go func () {
188
- pids , err := getAllProcesses (pid )
188
+ pids , err := psTree (pid )
189
189
if err != nil {
190
190
log .Fatalf ("getting all sub processes error: %v\n " , err )
191
191
return
@@ -232,28 +232,42 @@ func killProcess(pid int) (err error) {
232
232
return
233
233
}
234
234
235
- func getAllProcesses (pid int ) (pids []int , err error ) {
236
- tree , err := pstree .New ()
235
+ // implement pstree based on the cross-platform ps utility in go, go-ps
236
+ func psTree (rootPid int ) (res []int , err error ) {
237
+ pidOfInterest := map [int ]struct {}{rootPid : {}}
238
+ pss , err := ps .Processes ()
237
239
if err != nil {
238
- log . Fatalf ( "error: %v \n " , err )
240
+ fmt . Println ( "ERROR: " , err )
239
241
return
240
242
}
241
243
242
- traverseChildren (pid , tree , & pids )
243
- // we must kill the sub processes from smallest to largest
244
- sort .Ints (pids )
245
- return
246
- }
244
+ // we must sort the ps by ppid && pid first, otherwise we probably will miss some sub-processes
245
+ // of the root process during for-range searching
246
+ sort .Slice (pss , func (i , j int ) bool {
247
+ ppidLess := pss [i ].PPid () < pss [j ].PPid ()
248
+ pidLess := pss [i ].PPid () == pss [j ].PPid () && pss [i ].Pid () < pss [j ].Pid ()
249
+
250
+ return ppidLess || pidLess
251
+ })
252
+
253
+ for _ , ps := range pss {
254
+ ppid := ps .PPid ()
255
+ if _ , exists := pidOfInterest [ppid ]; exists {
256
+ pidOfInterest [ps .Pid ()] = struct {}{}
257
+ }
258
+ }
247
259
248
- func traverseChildren ( pid int , tree * pstree. Tree , curPids * [] int ) {
249
- for _ , cid := range tree . Procs [ pid ]. Children {
250
- * curPids = append (* curPids , cid )
251
- traverseChildren ( cid , tree , curPids )
260
+ for pid , _ := range pidOfInterest {
261
+ if pid != rootPid {
262
+ res = append (res , pid )
263
+ }
252
264
}
265
+
266
+ return
253
267
}
254
268
255
269
func waitForProcess (pid int , hasAllKilled chan bool ) (err error ) {
256
- pids , _ := getAllProcesses (pid )
270
+ pids , _ := psTree (pid )
257
271
if len (pids ) == 0 {
258
272
hasAllKilled <- true
259
273
return
0 commit comments