Created
February 13, 2023 15:57
-
-
Save xvzf/2a5d959cd8c876e1cb102cc4bcf1dfbb to your computer and use it in GitHub Desktop.
Redirect stdin when using exec
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" | |
"context" | |
"fmt" | |
"os/exec" | |
"sync" | |
"time" | |
) | |
const echoScript = `while read line | |
do | |
echo $line | |
done < /dev/stdin | |
` | |
func main() { | |
var wg sync.WaitGroup | |
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) | |
defer cancel() | |
var stdin bytes.Buffer | |
var stdout bytes.Buffer | |
cmd := exec.CommandContext(ctx, "bash", "-c", echoScript) | |
cmd.Stdin = &stdin | |
cmd.Stdout = &stdout | |
wg.Add(1) | |
go func() { | |
defer wg.Done() | |
cmd.Run() | |
}() | |
stdin.WriteString("Hello-World\n") | |
stdin.WriteString("This is a new line\n") | |
wg.Wait() | |
fmt.Println("Stdout:") | |
fmt.Println(stdout.String()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment