Last active
April 21, 2019 05:52
-
-
Save shirou/4fe0204a731e32e1f9a9f5735a1c9359 to your computer and use it in GitHub Desktop.
go version go1.11.1 linux/amd64 build with `go build -race`
This file contains hidden or 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" | |
"context" | |
"fmt" | |
"os/exec" | |
) | |
// copied from internal/common/common.go | |
// https://gist.github.com/kylelemons/1525278 | |
func Pipeline(cmds ...*exec.Cmd) ([]byte, []byte, error) { | |
// Require at least one command | |
if len(cmds) < 1 { | |
return nil, nil, nil | |
} | |
// Collect the output from the command(s) | |
var output bytes.Buffer | |
var stderr bytes.Buffer | |
last := len(cmds) - 1 | |
for i, cmd := range cmds[:last] { | |
var err error | |
// Connect each command's stdin to the previous command's stdout | |
if cmds[i+1].Stdin, err = cmd.StdoutPipe(); err != nil { | |
return nil, nil, err | |
} | |
// Connect each command's stderr to a buffer | |
cmd.Stderr = &stderr | |
} | |
// Connect the output and error for the last command | |
cmds[last].Stdout, cmds[last].Stderr = &output, &stderr | |
// Start each command | |
for _, cmd := range cmds { | |
if err := cmd.Start(); err != nil { | |
return output.Bytes(), stderr.Bytes(), err | |
} | |
} | |
// Wait for each command to complete | |
for _, cmd := range cmds { | |
if err := cmd.Wait(); err != nil { | |
return output.Bytes(), stderr.Bytes(), err | |
} | |
} | |
// Return the pipeline output and the collected standard error | |
return output.Bytes(), stderr.Bytes(), nil | |
} | |
func main() { | |
ctx := context.Background() | |
ls_bin, err := exec.LookPath("ls") | |
if err != nil { | |
panic(err) | |
} | |
echo_bin, err := exec.LookPath("echo") | |
if err != nil { | |
panic(err) | |
} | |
lsof := exec.CommandContext(ctx, ls_bin) | |
echo := exec.CommandContext(ctx, echo_bin) | |
output, _, err := Pipeline(lsof, echo) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println(string(output)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment