restictray/cmdtest/timeout.go

61 lines
1.1 KiB
Go

package main
import (
"bufio"
"fmt"
"os/exec"
"time"
)
func main() {
cmd := neverReturningThing()
//cmd := returningThingWithinThreeSecs()
//cmd := returningThingAfterThreeSecs()
stdout, _ := cmd.StdoutPipe()
busy := make(chan bool, 1)
cmd.Start()
scanner := bufio.NewScanner(stdout)
scanner.Split(bufio.ScanLines)
go func() {
fmt.Println("starting scanner.scan (blocking)")
for scanner.Scan() {
fmt.Println("scanned")
m := scanner.Text()
fmt.Println(m)
if busy != nil {
busy <- true
}
}
}()
fmt.Println("starting select chans")
var err error
select {
case <-busy:
fmt.Println("busy chan")
busy = nil
case <-time.After(3 * time.Second):
pkill := cmd.Process.Kill()
fmt.Println("timeout triggered? err: %w", pkill)
}
fmt.Println("starting Wait()")
err = cmd.Wait()
fmt.Printf("done? here's an error: %w", err)
}
func returningThingWithinThreeSecs() *exec.Cmd {
return exec.Command("echo", "sup")
}
func returningThingAfterThreeSecs() *exec.Cmd {
return exec.Command("ping", "google.com")
}
func neverReturningThing() *exec.Cmd {
return exec.Command("ssh", "user@unknown.local")
}