goroutine for command stdout capture

This commit is contained in:
Krumel
2021-06-02 23:41:27 +02:00
parent ee347acb96
commit 32f188f54a

View File

@ -5,7 +5,7 @@ import (
"fmt" "fmt"
"io" "io"
"log" "log"
"time"
// "math" // "math"
"container/ring" "container/ring"
"os/exec" "os/exec"
@ -24,30 +24,36 @@ func reload() {
} }
//builds the cmd which is called to run the server //builds the cmd which is called to run the server
func build_cmd() (string, string) { func build_cmd() (string, []string) {
return "ping", "-t 8.8.8.8" return "ping", []string{"-t", "8.8.8.8"}
} }
//run the server-thread //run the server-thread
func server_run() { func server_run() {
//create the command and start it //create the command
cmd_str, cmd_args := build_cmd() cmd_str, cmd_args := build_cmd()
cmd := exec.Command(cmd_str, cmd_args) cmd := exec.Command(cmd_str, cmd_args...)
err := cmd.Start()
if err != nil {
log.Panicln("Failed to call server command \"" + cmd.String() + "\"")
}
//connect pipes //connect pipes
stdout, err := cmd.StdoutPipe() stdout, err := cmd.StdoutPipe()
cmd.Stderr = cmd.Stdout cmd.Stderr = cmd.Stdout
srv_stdin, err = cmd.StdinPipe() //this one is global, because we write to it elsewhere srv_stdin, err = cmd.StdinPipe() //this one is global, because we write to it elsewhere
// run the process
err = cmd.Start()
if err != nil {
log.Panicln("Failed to call server command \"" + cmd.String() + "\"")
}
//read pipes and write them to the ring buffer //read pipes and write them to the ring buffer
buf := bufio.NewReader(stdout) buf := bufio.NewScanner(stdout)
for { for {
stdout_ring.Value, _, err = buf.ReadLine() if buf.Scan() {
stdout_ring.Value = buf.Text()
stdout_ring = stdout_ring.Next() stdout_ring = stdout_ring.Next()
} else {
time.Sleep(300 * time.Millisecond)
}
} }
} }
@ -60,12 +66,17 @@ func refresh(g *gocui.Gui) error {
} }
v.Clear() v.Clear()
vW, vH := v.Size() _, vH := v.Size()
r := stdout_ring r := stdout_ring
v.Overwrite = true
for i := 0; i < vH; i++ { for i := 0; i < vH; i++ {
fmt.Fprintln(v, r.Value) v.SetCursor(4, vH - i)
if r.Value != nil {
fmt.Fprint(v, r.Value)
}
r = r.Prev() r = r.Prev()
} }
@ -92,6 +103,9 @@ func main() {
log.Panicln(err) log.Panicln(err)
} }
go server_run()
//run the CUI main loop
if err := g.MainLoop(); err != nil && err != gocui.ErrQuit { if err := g.MainLoop(); err != nil && err != gocui.ErrQuit {
log.Panicln(err) log.Panicln(err)
} }
@ -101,15 +115,14 @@ func main() {
func layout(g *gocui.Gui) error { func layout(g *gocui.Gui) error {
maxX, maxY := g.Size() maxX, maxY := g.Size()
if v, err := g.SetView("srv_log", 0, 0, maxX-1, int(float32(maxY) * 0.8)); err != nil { if _, err := g.SetView("srv_log", 0, 0, maxX-1, int(float32(maxY) * 0.8)); err != nil {
if err != gocui.ErrUnknownView { if err != gocui.ErrUnknownView {
return err return err
} }
str, _ := settings.ToTomlString();
fmt.Fprintln(v, str)
} }
refresh(g)
return nil return nil
} }