mediamtx/internal/externalcmd/cmd.go

78 lines
1014 B
Go
Raw Normal View History

package externalcmd
import (
"time"
)
const (
restartPause = 5 * time.Second
)
2020-11-21 12:35:33 +00:00
// Environment is a Cmd environment.
2020-11-01 16:33:06 +00:00
type Environment struct {
Path string
Port string
}
2020-11-21 12:35:33 +00:00
// Cmd is an external command.
type Cmd struct {
2020-11-01 16:33:06 +00:00
cmdstr string
restart bool
env Environment
// in
terminate chan struct{}
// out
done chan struct{}
}
2020-11-21 12:35:33 +00:00
// New allocates an Cmd.
func New(cmdstr string, restart bool, env Environment) *Cmd {
e := &Cmd{
cmdstr: cmdstr,
restart: restart,
2020-11-01 16:33:06 +00:00
env: env,
terminate: make(chan struct{}),
done: make(chan struct{}),
}
go e.run()
2021-08-01 14:58:46 +00:00
return e
}
2020-11-21 12:35:33 +00:00
// Close closes an Cmd.
func (e *Cmd) Close() {
close(e.terminate)
<-e.done
}
2020-11-21 12:35:33 +00:00
func (e *Cmd) run() {
defer close(e.done)
for {
2020-10-31 16:03:03 +00:00
ok := func() bool {
ok := e.runInner()
if !ok {
return false
}
2020-10-31 16:03:03 +00:00
if !e.restart {
<-e.terminate
return false
}
2020-10-31 16:03:03 +00:00
select {
case <-time.After(restartPause):
2020-10-31 16:03:03 +00:00
return true
case <-e.terminate:
return false
}
}()
if !ok {
break
}
}
}