gobyexample/spawn/spawn.go

56 lines
1.1 KiB
Go
Raw Normal View History

2024-05-13 08:24:31 +00:00
package spawn
import (
"fmt"
"io"
"os/exec"
)
func Spawn() {
// Cmd object represents the external process
dateCmd := exec.Command("date")
// Runs and wait for it to finish, output collected
dateOut, err := dateCmd.Output()
if err != nil {
panic(err)
}
fmt.Println("> date")
fmt.Println(string(dateOut))
_, err = exec.Command("date", "-x").Output()
if err != nil {
switch e := err.(type) {
case *exec.Error:
fmt.Println("failed executing:", err)
case *exec.ExitError:
fmt.Println("command exit code:", e.ExitCode())
default:
panic(err)
}
}
grepCmd := exec.Command("grep", "hello")
grepIn, _ := grepCmd.StdinPipe()
grepOut, _ := grepCmd.StdoutPipe()
grepCmd.Start()
grepIn.Write([]byte("hello world\ngoodbye grep\nI am Jin, hello"))
grepIn.Close()
grepBytes, _ := io.ReadAll(grepOut)
grepCmd.Wait()
fmt.Println("> grep hello")
fmt.Println(string(grepBytes))
lsCmd := exec.Command("bash", "-c", "ls -a -l -h")
lsOut, err := lsCmd.Output()
if err != nil {
panic(err)
}
fmt.Println("> ls -a -l -h")
fmt.Println(string(lsOut))
}