I'm trying to use Go's os/exec Command()
to simulate a keypress, and sometimes I'll want to use this keypress multiple times in quick succession. I'm using exec.Command
to call "xte", "key XF86AudioPlay", which pauses music on a Linux OS. While the Command
can Start()
or Run()
no problem, if I try to execute again, I get an error:
exec: already started
I've tried using Process.Kill()
immediately after the execution, in order to free it up, but this will make the execution not work in the first place. I got this idea from here: Terminating a Process Started with os/exec in Golang
My code uses a switch
and calls this pause function accordingly, but I'll simply share the basis of the code I wrote, with the case
as an example function:
cmd := exec.Command("xte", "key XF86AudioPlay")
//...
func Pause() {
err := cmd.Start() // or cmd.Run()
if err != nil {
fmt.Println(err)
}
err = cmd.Process.Kill()
if err != nil {
fmt.Printf("Failed to kill: %s", err)
}
}
So, to recap, I'm successful at calling it one time, but upon success calls to Pause()
, I get the error from cmd.Start()
/Run()
which read: exec: already started
.
I also tried going lower, that is, using syscall
, but I ran into some trouble. I tried:
args[0] = "xte"
args[1] = "key"
args[2] = "XF86AudioPlay"
//... Pause():
err := syscall.Exec("/bin", args, os.Environ())
if err != nil {
fmt.Println(err)
}
And here I got a permission denied
error, even running as super user (sudo).
How should I proceed call this Command()
and then free it up for immediate recall? Or am I on the right track with syscall
?
Edit
So the solution as both Amd and Son Bui state, was to create the Command
everytime I intend to call it, basically putting the assignment cmd := exec.Command()
inside my Pause()
method.