Skip to content

Instantly share code, notes, and snippets.

@VillanCh
Created April 22, 2018 06:41
Show Gist options
  • Save VillanCh/1dc24b0fb55b4a4a02fab464ec67aef1 to your computer and use it in GitHub Desktop.
Save VillanCh/1dc24b0fb55b4a4a02fab464ec67aef1 to your computer and use it in GitHub Desktop.
Golang: Execute with a Timeout
package main
import (
"bytes"
"fmt"
"os/exec"
"time"
)
type killCmdForce func(exec.Cmd)
func main() {
cmd := exec.Command("nmap", "127.0.0.1", "-oX", "-", "-p", "0-65535")
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
result_chan := make(chan error)
defer close(result_chan)
go func() {
result_chan <- cmd.Run()
}()
select {
case err := <-result_chan:
if err != nil {
fmt.Println(err)
} else {
xmlNmap := string(stdout.Bytes())
fmt.Print(xmlNmap)
}
case <-time.After(10 * time.Second):
cmd.Process.Kill()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment