/
local_process.go
56 lines (48 loc) · 1.55 KB
/
local_process.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package testutils
import (
"os"
"runtime"
"strconv"
"strings"
"syscall"
"github.com/pkg/errors"
"golang.org/x/crypto/ssh"
)
// GetTestSessionProcess returns the process belonging to an ssh session.
// If the process can not be found panic() is called.
//
// The session is assumed to run on the same host as where this function is called.
// The session is furthermore assumed to use a bash-compatible shell and that the '$$' variable returns the process id.
//
// This function is itself untested.
func GetTestSessionProcess(session *ssh.Session) *os.Process {
// get the pid of the session
pidBytes, err := session.Output("echo $$")
if err != nil {
panic(errors.Wrap(err, "Unable to get pid via session"))
}
// get the int of the pid
pid, err := strconv.ParseInt(strings.TrimSpace(string(pidBytes)), 10, 32)
if err != nil {
panic(errors.Wrap(err, "pid was not an int"))
}
// get the process itself
proc, err := os.FindProcess(int(pid))
if err != nil {
panic(errors.Wrap(err, "Can not find process"))
}
return proc
}
// IsProcessAlive checks if the process refered to by the argument is still alive.
//
// This function relies on the fact that the underlying operating system supports sending signals to the process.
// On Windows and Plan 9 this function may panic, as it can not be used.
//
// This function is itself untested.
func IsProcessAlive(proc *os.Process) (res bool) {
if runtime.GOOS == "windows" || runtime.GOOS == "plan9" {
panic("GOOS unsupported")
}
defer func() { recover() }()
return proc.Signal(syscall.Signal(0)) == nil
}