Last active
January 29, 2019 12:31
-
-
Save LittleKey/8b48462f8e89287fb24f8a8c024a7f3f to your computer and use it in GitHub Desktop.
execute shell command n times
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 ( | |
"flag" | |
"fmt" | |
"io" | |
"os/exec" | |
"strings" | |
"time" | |
) | |
// Read out bytes and write to ch with blocking. | |
func Read(ch chan<- []byte, out io.ReadCloser) { | |
defer out.Close() | |
for { | |
buffer := make([]byte, 4096) | |
out.Read(buffer) | |
ch <- buffer | |
} | |
} | |
// Print ch bytes with blocking. | |
func Print(ch <-chan []byte) { | |
for { | |
select { | |
case buf := <-ch: | |
fmt.Print(string(buf)) | |
} | |
} | |
} | |
func main() { | |
times := flag.Int("times", 1, "execute times of app.") | |
flag.Parse() | |
args := flag.Args() | |
if len(args) < 1 { | |
fmt.Println("Missing app name") | |
return | |
} | |
// New channel to read and print stdout from command app. | |
ch := make(chan []byte, 10) | |
defer close(ch) | |
// Print command stdout from ch | |
go Print(ch) | |
for i := 0; i < *times; i++ { | |
fmt.Printf("Current execute \"%v\" %d times\n", strings.Join(args, " "), i+1) | |
cmd := exec.Command(args[0], args[1:]...) | |
stdout, err := cmd.StdoutPipe() | |
if err != nil { | |
fmt.Printf("Pipe stdout got error: %v", err.Error()) | |
return | |
} | |
stderr, err := cmd.StderrPipe() | |
if err != nil { | |
fmt.Printf("Pipe stderr got error: %v", err.Error()) | |
return | |
} | |
// Read command stdout | |
go Read(ch, stdout) | |
// Read command stderr | |
go Read(ch, stderr) | |
cmd.Run() | |
cmd.Wait() | |
time.Sleep(100 * time.Millisecond) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment