### 衍生(Spawn)新進程
這是來自GoByExample的例子,代碼在[https://gobyexample.com/spawning-processes](https://gobyexample.com/spawning-processes)。
它能夠執行任意Go或者非Go程序,并且等待放回結果,外部進程結束后繼續執行本程序。
### 代碼實現
~~~
package main
import "fmt"
import "io/ioutil"
import "os/exec"
func main() {
dateCmd := exec.Command("date")
dateOut, err := dateCmd.Output()
if err != nil {
panic(err)
}
fmt.Println("> date")
fmt.Println(string(dateOut))
grepCmd := exec.Command("grep", "hello")
grepIn, _ := grepCmd.StdinPipe()
grepOut, _ := grepCmd.StdoutPipe()
grepCmd.Start()
grepIn.Write([]byte("hello grep\ngoodbye grep"))
grepIn.Close()
grepBytes, _ := ioutil.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))
}
~~~
### 運行結果
~~~
$ go run spawning-processes.go
> date
Wed Oct 10 09:53:11 PDT 2012
> grep hello
hello grep
> 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
~~~
### 歸納總結
因此如果你的程序需要執行外部命令,可以直接使用`exec.Command()`來Spawn進程,并且根據需要獲得外部程序的返回值。
- 前言
- 致謝
- 概述
- 使用代碼
- 使用Docker
- 進程基礎
- 進程是什么
- Hello World
- PID
- PPID
- 使用PID
- 進程名字
- 進程參數
- 輸入與輸出
- 并發與并行
- 進程越多越好
- 進程狀態
- 退出碼
- 進程資源
- 死鎖
- 活鎖
- POSIX
- Nohup
- 運行進程
- Go編程實例
- 衍生新進程
- 執行外部程序
- 復制進程
- 進程進階
- 文件鎖
- 孤兒進程
- 僵尸進程
- 守護進程
- 進程間通信
- 信號
- Linux系統調用
- 文件描述符
- Epoll
- 共享內存
- Copy On Write
- Cgroups
- Namespaces
- 項目實例Run
- 項目架構
- 代碼實現
- 注意事項
- 創建目錄權限
- 捕獲SIGKILL
- Sendfile系統調用
- 后記
- 參考書籍
- 項目學習
- 再次感謝