Skip to content

Commit 3dc094f

Browse files
committed
78: Spawning example with piping
1 parent 8d95c63 commit 3dc094f

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

execingprocesses/main.go

+1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package execingprocesses
22

3+
// Similarly to spawning a subprocess
34
func Run() {
45

56
}

spawningprocesses/main.go

+16
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package spawningprocesses
22

33
import (
44
"fmt"
5+
"io"
56
"os/exec"
67
)
78

@@ -14,6 +15,21 @@ func Run() {
1415
commandWithArgs("date", "-u")
1516
// error with args:
1617
commandWithArgs("date", "-x")
18+
// piping basics
19+
commandWithPiping("grep", "hello")
20+
}
21+
22+
func commandWithPiping(cmd string, args ...string) {
23+
grepCommand := exec.Command(cmd, args...)
24+
in, _ := grepCommand.StdinPipe()
25+
out, _ := grepCommand.StdoutPipe()
26+
grepCommand.Start()
27+
in.Write([]byte("hello grep\ngoodbye grep"))
28+
in.Close()
29+
grepBytes, _ := io.ReadAll(out)
30+
grepCommand.Wait()
31+
fmt.Println("> grep hello")
32+
fmt.Println(string(grepBytes))
1733
}
1834

1935
// A very basic command without any flags/args provided.

0 commit comments

Comments
 (0)