|
I need to test if the server terminal is closing as expected when a SIGINT (ctrl+c) is received but I do not have any pc running macOS. First of all make sure that it is compiled successfully. (if you can send me the output of the run thanks) @f8ith if you could test it, it would be great thanks (this question is still open for other testers) This is the snippet of code to test: package main
import (
"bufio"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"strings"
"sync"
"syscall"
"time"
)
var serverDir = "path/to/server/folder"
var cmd *exec.Cmd
var wg sync.WaitGroup
var stdOut io.ReadCloser
var stdErr io.ReadCloser
var stdIn io.WriteCloser
var lastLine = make(chan string)
func main() {
interruptListener()
cSplit := strings.Split("java -Xmx1024M -Xms1024M -jar server.jar nogui", " ")
cmd = exec.Command(cSplit[0], cSplit[1:]...)
cmd.Dir = serverDir
// launch as new process group so that signals (ex: SIGINT) are not sent also the the child process
cmd.SysProcAttr = &syscall.SysProcAttr{
// windows //
// CreationFlags: syscall.CREATE_NEW_PROCESS_GROUP,
// linux //
Setpgid: true,
}
stdOut, _ = cmd.StdoutPipe()
stdErr, _ = cmd.StderrPipe()
stdIn, _ = cmd.StdinPipe()
wg.Add(2)
go printer(stdOut)
go printer(stdErr)
err := cmd.Start()
if err != nil {
fmt.Println(err)
}
// here user sends SIGINT (ctrl+c)
time.Sleep(40 * time.Second)
out := execute("stop")
if strings.Contains(out, "Stopping the server") {
wg.Wait()
os.Exit(0)
} else {
fmt.Println("server does not seem to be stopping, is the stop command correct?")
}
}
func printer(stdP io.ReadCloser) {
var line string
defer wg.Done()
scanner := bufio.NewScanner(stdP)
for scanner.Scan() {
line = scanner.Text()
fmt.Println(line)
select {
case lastLine <- line:
default:
}
}
fmt.Printf("scanner error: %v\n", scanner.Err())
}
// execute returns the first line of the command issued
func execute(com string) string {
fmt.Println("sending", com, "to terminal")
// needs to be added otherwise the virtual "enter" button is not pressed
com += "\n"
_, err := stdIn.Write([]byte(com))
if err != nil {
fmt.Println(err.Error())
}
return <-lastLine
}
func interruptListener() {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
go func() {
select {
case <-c:
out := execute("stop")
if strings.Contains(out, "Stopping") {
wg.Wait()
os.Exit(0)
} else {
fmt.Println("server does not seem to be stopping, is the stopForce command correct?")
}
}
}()
} |
Answered by
gekigek99
Mar 1, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The functionality of the script was checked and confirmed
reference: d41e3b2