# Go 進程觸發
有的時候,我們需要從Go程序里面觸發一個其他的非Go進程來執行。
```go
package main
import "fmt"
import "io/ioutil"
import "os/exec"
func main() {
// 我們從一個簡單的命令開始,這個命令不需要任何參數
// 或者輸入,僅僅向stdout輸出一些信息。`exec.Command`
// 函數創建了一個代表外部進程的對象
dateCmd := exec.Command("date")
// `Output`是另一個運行命令時用來處理信息的函數,這個
// 函數等待命令結束,然后收集命令輸出。如果沒有錯誤發
// 生的話,`dateOut`將保存date的信息
dateOut, err := dateCmd.Output()
if err != nil {
panic(err)
}
fmt.Println("> date")
fmt.Println(string(dateOut))
// 下面我們看一個需要從stdin輸入數據的命令,我們將
// 數據輸入傳給外部進程的stdin,然后從它輸出到stdout
// 的運行結果收集信息
grepCmd := exec.Command("grep", "hello")
// 這里我們顯式地獲取input/output管道,啟動進程,
// 向進程寫入數據,然后讀取輸出結果,最后等待進程結束
grepIn, _ := grepCmd.StdinPipe()
grepOut, _ := grepCmd.StdoutPipe()
grepCmd.Start()
grepIn.Write([]byte("hello grep\ngoodbye grep"))
grepIn.Close()
grepBytes, _ := ioutil.ReadAll(grepOut)
grepCmd.Wait()
// 在上面的例子中,我們忽略了錯誤檢測,但是你一樣可以
// 使用`if err!=nil`模式來進行處理。另外我們僅僅收集了
// `StdoutPipe`的結果,同時你也可以用一樣的方法來收集
// `StderrPipe`的結果
fmt.Println("> grep hello")
fmt.Println(string(grepBytes))
// 注意,我們在觸發外部命令的時候,需要顯式地提供
// 命令和參數信息。另外如果你想用一個命令行字符串
// 觸發一個完整的命令,你可以使用bash的-c選項
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))
}
```
所觸發的程序的執行結果和我們直接執行這些程序的結果是一樣的。
運行結果
```
> 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
```
- 版權
- 內容
- Go常量
- Go變量
- Go 數值
- Go 數組
- Go 字典
- Go 函數定義
- Go 方法
- Go 結構體
- Go 閉包函數
- Go 接口
- Go 字符串操作函數
- Go 字符串格式化
- Go 自定義排序
- Go Base64編碼
- Go Defer
- Go Exit.md
- Go for循環
- Go if..else if..else 條件判斷
- Go JSON支持
- Go Line Filters
- Go 狀態協程
- Go Panic
- Go range函數
- Go SHA1 散列
- Go String與Byte切片之間的轉換
- Go Switch語句
- Go URL解析
- Go 遍歷通道
- Go 并行功能
- Go 并行通道Channel
- Go 超時
- Go 錯誤處理
- Go 打點器
- Go 遞歸函數
- Go 讀取文件
- Go 工作池
- Go 關閉通道
- Go 函數多返回值
- Go 函數回調
- Go 函數命名返回值
- Go 互斥
- Go 環境變量
- Go 集合功能
- Go 計時器
- Go 進程觸發
- Go 進程執行
- Go hello world
- Go 可變長參數列表
- Go 命令行參數
- Go 命令行參數標記
- Go 排序
- Go 切片
- Go 請求處理頻率控制
- Go 時間
- Go 時間戳
- Go 時間格式化和解析
- Go 數字解析
- Go 隨機數
- Go 通道的同步功能
- Go 通道方向
- Go 通道緩沖
- Go 通道選擇Select
- Go 寫入文件
- Go 信號處理
- Go 原子計數器
- Go 正則表達式
- Go 指針