衍生(Spawn)新进程

这是来自GoByExample的例子,代码在https://gobyexample.com/spawning-processes

它能够执行任意Go或者非Go程序,并且等待返回结果,外部进程结束后继续执行本程序。

代码实现

  1. package main
  2. import "fmt"
  3. import "io/ioutil"
  4. import "os/exec"
  5. func main() {
  6. dateCmd := exec.Command("date")
  7. dateOut, err := dateCmd.Output()
  8. if err != nil {
  9. panic(err)
  10. }
  11. fmt.Println("> date")
  12. fmt.Println(string(dateOut))
  13. grepCmd := exec.Command("grep", "hello")
  14. grepIn, _ := grepCmd.StdinPipe()
  15. grepOut, _ := grepCmd.StdoutPipe()
  16. grepCmd.Start()
  17. grepIn.Write([]byte("hello grep\ngoodbye grep"))
  18. grepIn.Close()
  19. grepBytes, _ := ioutil.ReadAll(grepOut)
  20. grepCmd.Wait()
  21. fmt.Println("> grep hello")
  22. fmt.Println(string(grepBytes))
  23. lsCmd := exec.Command("bash", "-c", "ls -a -l -h")
  24. lsOut, err := lsCmd.Output()
  25. if err != nil {
  26. panic(err)
  27. }
  28. fmt.Println("> ls -a -l -h")
  29. fmt.Println(string(lsOut))
  30. }

运行结果

  1. $ go run spawning-processes.go
  2. > date
  3. Wed Oct 10 09:53:11 PDT 2012
  4. > grep hello
  5. hello grep
  6. > ls -a -l -h
  7. drwxr-xr-x 4 mark 136B Oct 3 16:29 .
  8. drwxr-xr-x 91 mark 3.0K Oct 3 12:50 ..
  9. -rw-r--r-- 1 mark 1.3K Oct 3 16:28 spawning-processes.go

归纳总结

因此如果你的程序需要执行外部命令,可以直接使用exec.Command()来Spawn进程,并且根据需要获得外部程序的返回值。