Created
April 22, 2018 06:41
-
-
Save VillanCh/1dc24b0fb55b4a4a02fab464ec67aef1 to your computer and use it in GitHub Desktop.
Golang: Execute with a Timeout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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