2016-02-16 23:13:18 +00:00
|
|
|
// +build !windows
|
|
|
|
|
2016-11-29 23:38:24 +00:00
|
|
|
package sys
|
2016-01-06 21:32:46 +00:00
|
|
|
|
2016-04-04 18:23:40 +00:00
|
|
|
import "syscall"
|
2016-01-06 21:32:46 +00:00
|
|
|
|
|
|
|
// Exit is the wait4 information from an exited process
|
|
|
|
type Exit struct {
|
|
|
|
Pid int
|
|
|
|
Status int
|
|
|
|
}
|
|
|
|
|
|
|
|
// Reap reaps all child processes for the calling process and returns their
|
|
|
|
// exit information
|
2016-09-12 18:22:48 +00:00
|
|
|
func Reap(wait bool) (exits []Exit, err error) {
|
2016-01-06 21:32:46 +00:00
|
|
|
var (
|
|
|
|
ws syscall.WaitStatus
|
|
|
|
rus syscall.Rusage
|
|
|
|
)
|
2016-09-12 18:22:48 +00:00
|
|
|
flag := syscall.WNOHANG
|
|
|
|
if wait {
|
|
|
|
flag = 0
|
|
|
|
}
|
2016-01-06 21:32:46 +00:00
|
|
|
for {
|
2016-09-12 18:22:48 +00:00
|
|
|
pid, err := syscall.Wait4(-1, &ws, flag, &rus)
|
2016-01-06 21:32:46 +00:00
|
|
|
if err != nil {
|
|
|
|
if err == syscall.ECHILD {
|
|
|
|
return exits, nil
|
|
|
|
}
|
|
|
|
return exits, err
|
|
|
|
}
|
|
|
|
if pid <= 0 {
|
|
|
|
return exits, nil
|
|
|
|
}
|
|
|
|
exits = append(exits, Exit{
|
|
|
|
Pid: pid,
|
2016-04-04 18:23:40 +00:00
|
|
|
Status: exitStatus(ws),
|
2016-01-06 21:32:46 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
2016-04-04 18:23:40 +00:00
|
|
|
|
|
|
|
const exitSignalOffset = 128
|
|
|
|
|
|
|
|
// exitStatus returns the correct exit status for a process based on if it
|
|
|
|
// was signaled or exited cleanly
|
|
|
|
func exitStatus(status syscall.WaitStatus) int {
|
|
|
|
if status.Signaled() {
|
|
|
|
return exitSignalOffset + int(status.Signal())
|
|
|
|
}
|
|
|
|
return status.ExitStatus()
|
|
|
|
}
|