lean into examples
This commit is contained in:
36
examples/spawning-processes/spawning-processes.go
Normal file
36
examples/spawning-processes/spawning-processes.go
Normal file
@@ -0,0 +1,36 @@
|
||||
// Sometimes our Go programs need to spawn other, non-Go
|
||||
// processes. For example, the syntax highlighting in this
|
||||
// book is implementing by spawning a [`pygmentize`]()
|
||||
// process from a Go program. Let's look at a few
|
||||
// examples of spawning processes from Go.
|
||||
|
||||
package main
|
||||
|
||||
import "os/exec"
|
||||
import "fmt"
|
||||
|
||||
func main() {
|
||||
// todo: explain
|
||||
dateCmd := exec.Command("date")
|
||||
dateOut, dateErr := dateCmd.Output()
|
||||
if dateErr != nil {
|
||||
panic(dateErr)
|
||||
}
|
||||
fmt.Println("> date")
|
||||
fmt.Println(string(dateOut))
|
||||
|
||||
// todo: piping in stdin
|
||||
|
||||
// Note that when spawning commands we need to
|
||||
// provide an explicit command and argument array,
|
||||
// vs. being able to just pass in one command line.
|
||||
// If you want to be able to just spawn a full
|
||||
// command, you can use `bash`'s `-c` option:
|
||||
lsCmd := exec.Command("bash", "-c", "ls -a -l -h")
|
||||
lsOut, lsErr := lsCmd.Output()
|
||||
if lsErr != nil {
|
||||
panic(lsErr)
|
||||
}
|
||||
fmt.Println("> ls -a -l -h")
|
||||
fmt.Println(string(lsOut))
|
||||
}
|
||||
8
examples/spawning-processes/spawning-processes.sh
Normal file
8
examples/spawning-processes/spawning-processes.sh
Normal file
@@ -0,0 +1,8 @@
|
||||
$ go run spawning-processes.go
|
||||
> date
|
||||
Wed Oct 3 16:40:57 EDT 2012
|
||||
|
||||
> ls -a -l -h
|
||||
drwxr-xr-x 4 mark 136B Oct 3 16:29 .
|
||||
drwxr-xr-x 91 mark 3.0K Oct 3 12:50 ..
|
||||
-rw-r--r-- 1 mark 1.3K Oct 3 16:28 spawning-processes.go
|
||||
Reference in New Issue
Block a user