package main
import (
"fmt"
"os/exec"
)
func main() {
var (
cmd *exec.Cmd
err error
)
cmd = exec.Command("/bin/bash", "-c", "echo 1")
err = cmd.Run()
fmt.Println(err)
}
package main
import (
"fmt"
"os/exec"
)
func main() {
var (
cmd *exec.Cmd
output []byte
err error
)
// 生成Cmd
cmd = exec.Command("/bin/bash", "-c", "ls -la /")
// 執(zhí)行了命令, 捕獲了子進程的輸出( pipe )
if output, err = cmd.CombinedOutput(); err != nil {
fmt.Println(err)
return
}
//打印子進程的輸出
fmt.Println(string(output))
}
goroutine執(zhí)行l(wèi)inux命令,睡了2秒。而main睡一秒就殺死了bash,輸出結(jié)果為:signal: killed:
成都創(chuàng)新互聯(lián)是一家專注于網(wǎng)站設(shè)計制作、網(wǎng)站制作與策劃設(shè)計,閔行網(wǎng)站建設(shè)哪家好?成都創(chuàng)新互聯(lián)做網(wǎng)站,專注于網(wǎng)站建設(shè)十余年,網(wǎng)設(shè)計領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:閔行等地區(qū)。閔行做網(wǎng)站價格咨詢:13518219792
package main
import (
"context"
"fmt"
"os/exec"
"time"
)
type result struct {
err error
output []byte
}
func main() {
//執(zhí)行一個cmd,讓它在一個協(xié)程里執(zhí)行,讓它執(zhí)行2秒
//1秒的時候,我們殺死cmd
var (
ctx context.Context
cancelFunc context.CancelFunc
cmd *exec.Cmd
resultChan chan *result
res *result
)
//創(chuàng)建一個結(jié)果隊列
resultChan = make(chan *result, 1000)
//context里有個channel,返回一個cancelFunc來關(guān)掉channel
//context.上下文繼承了context.TODO()上下文
ctx,cancelFunc = context.WithCancel(context.TODO())
go func() {
var (
output []byte
err error
)
//exec.Command()是沒辦法被取消的
cmd = exec.CommandContext(ctx,"/bin/bash", "-c", "sleep 2;echo hello;") //里面有個select{case <- ctx.Done()},一旦檢測到調(diào)用了cancelFunc,則kill掉bash程序(kill pid,進程id,殺死子進程)
//執(zhí)行任務(wù),捕獲輸出
output, err = cmd.CombinedOutput()
//把任務(wù)輸出結(jié)果傳給main協(xié)程
resultChan <- &result{
err: err,
output: output,
}
}()
//繼續(xù)往下走
time.Sleep(1 * time.Second)
//取消上下文
cancelFunc()
//在main協(xié)程里, 等待子協(xié)程的退出,并打印任務(wù)執(zhí)行結(jié)果
res = <- resultChan
// 打印任務(wù)執(zhí)行結(jié)果
fmt.Println(res.err, string(res.output))
}